% SPDX-License-Identifier: Beerware
% Wolfgang DM5WK Kroener wrote this file. As long as you retain this notice you
% can do whatever you want with this stuff. If we meet some day, and you think
% this stuff is worth it, you can buy me a beer in return.

% needed because pgf also loads xcolor with different options
\PassOptionsToPackage{svgnames}{xcolor}

\documentclass[12pt]{article}

%
% configure settings here
%
% configure paperformat here
\def\paper{a4paper}
\newlength{\rowheight}
% configure height of lines
\setlength{\rowheight}{9mm}
% configure number of table blocks on each page
\def\numtables{2}
% margins of paper defined above
\usepackage[\paper, hmargin=0.7cm, vmargin=0.9cm]{geometry}
% layout of pages (with pgfmorepages)
% valid settings e. g. 2 on 1, 4 on 1, 6 on 1, 8 on 1, 16 on 1
\usepackage{pgfmorepages}
\pgfpagesuselayout{2 on 1}[\paper, landscape]

% how many pages (duplex printing with \pgflayout 2 on 1 can fit 4 pages
% but maybe more numerated pages are needed
% you may run out of memory for latex, maybe try lualatex
\def\numpages{4}
% define callsign here or with filename
% e. g. \def\callsign{AB1CD}
% if you define it here, callsign will not be taken from filename
\def\callsign{}
% is this for trainee logging?
% set \trainee to trainee for trainee callsign
% or to stroketrainee to get \callsign/T
% if you define it here, trainee will not be taken from filename
\def\trainee{}

%
% normally no configuration below this line
%

\usepackage[utf8]{inputenc}
\usepackage{lmodern}


\usepackage{tabularray}
\UseTblrLibrary{functional}
\usepackage{functional}
\NewColumnType{Y}{Q[c,m]}
\NewColumnType{Z}{X[c,m]}

\usepackage{pgffor}
\usepackage{xstring}
\usepackage{fp}
% strip dimension of length and convert to mm
\ExplSyntaxOn
\newcommand\stripdim[1]{\dim_to_decimal_in_unit:nn{#1}{1mm}}
\ExplSyntaxOff

%split \jobname, extract after first dot callsign, after second dot: trainee
% e. g. for logsheet.AB0CD.trainee.tex extract \callsign as AB0CD and \trainee as trainee
% e. g. for logsheet.AB0CD.tex extract \callsign as AB0CD and \trainee is empty
% put \callsign in watermark and add +OP in heading if \trainee equals trainee
\StrCut{\jobname}{.}\strA\strB
\StrLen{\callsign}[\lenTemp]
\IfEq{\lenTemp}{0}{
  \StrCut{\strB}{.}\callsign\strC
}{
  \StrCut{\strB}{.}\strTemp\strC
}


\newif\ifistrainee
% default is false
\istraineefalse

% add /t to callsign if filename is logsheet.CALLSIGN.stroketrainee.tex
% set istrainee to true if applicable
% strange things with detokenize needed with latex
\StrLen{\trainee}[\lenTemp]
\IfEq{\lenTemp}{0}{
  \StrCut{\strC}{.}\trainee\strD
  \IfStrEq{\trainee}{\detokenize{trainee}}{
    \istraineetrue
  }{
    \IfStrEq{\trainee}{\detokenize{stroketrainee}}{
      \istraineetrue
      \edef\callsign{\callsign/T}
    }{}
  }
}{
  \IfStrEq{\trainee}{trainee}{
    \istraineetrue
  }{
    \IfStrEq{\trainee}{stroketrainee}{
      \istraineetrue
      \edef\callsign{\callsign/T}
    }{}
  }
}


% default scale if there is no callsign (\wmfontscale\paperwidth)
\FPset\wmfontscale{0.25}

\StrLen{\callsign}[\callsignlen]
% calculations for callsign as watermark if there is one
\IfEq{\callsignlen}{0}{}{
  % calculate factor for fontsize for diagonal watermark
  % (sqrt(w^2+h^2))/(w * factor * callsignlen)
  % factor is for callsign going more or less over the whole diagonal
  \FPset\w{\stripdim{\paperwidth}}
  \FPset\h{\stripdim{\paperheight}}
  \FPeval\wmfontscale{root(2,pow(2,h)+pow(2,w))/(w * 0.65 * callsignlen)}

  % calculate angle for diagonal text
  \FPeval\diagonalAngle{arctan(h/w) * 180/FPpi}
}

% pagenumber as watermark
\FPeval\wmfontscalepagenumber{0.75*wmfontscale}
\usepackage{xcolor}
\usepackage{eso-pic}
\usepackage{tikz}
\usetikzlibrary{calc}
\tikzset{every picture/.style={gray, opacity=0.1}}
\newcommand\wmpagenumber{%
  \AddToShipoutPictureBG*{%
    \begin{tikzpicture}[overlay]
      % first pagenumber
      \node at ($(current page.north west)!.5!(current page.center)$)
      [font=\fontsize{\wmfontscalepagenumber\paperwidth}{\wmfontscalepagenumber\paperwidth}]
      {\bfseries\the\numexpr\thepage};
      % then callsign if there is one
      \IfEq{\callsignlen}{0}{}{
        \node at (current page.center)
        [rotate=\diagonalAngle, font=\fontsize{\wmfontscale\paperwidth}{\wmfontscale\paperwidth}]
        {\bfseries\callsign};
      }
      %\draw[red,step=1mm] (0,0) grid (40,40);
    \end{tikzpicture}
  }
}

\pagestyle{empty}
\setlength\parindent{0pt}

% calculate, how many lines fit on the paper
\FPset\htext{\stripdim{\textheight}}
\FPset\hlines{\stripdim{\rowheight}}
\FPset\hru{\stripdim{\arrayrulewidth}}
\FPeval\tablelines{trunc((htext/(hlines+hru)), 0)}
\FPeval\tablelinesPlusTwo{round(tablelines + 2, 0)}
\FPeval\tablelinesPlusFour{round(tablelines + 4, 0)}

% add +OP on trainee sheet
\ifistrainee
  \def\locationOp{Location+OP}
\else
  \def\locationOp{Location}
\fi

% add content of table, create #2 times #1/#2 rows, #1/#2 including two header rows
\prgNewFunction \makerows{mm} {
  \tlClear \lTmpaTl
  \intZero \lTmpaInt
  \intStepInline {1} {1} {#1} {
    \boolSet \lTmpaBool {\intCompare {\intMathMod{##1-1}{#1 / #2}} = {0} && \intCompare{#1-##1} > {2}}
    \boolVarIfTF \lTmpaBool {
      \intZero \lTmpaInt
      % heading
      \tlPutRight \lTmpaTl {\SetVline[=]{##1}{0pt} \SetCell[r=1,c=5]{valign=m,c} \begin{tblr}{colsep=0pt,width=\textwidth,rows={\rowheight},colspec={X[l,m]Q[r,m]}}Date: \hspace*{4cm} \locationOp: & Mode: \hspace*{2cm} \end{tblr}&&&&& \SetVline[=]{##1}{0pt}\\}
    }{
      \intCompareTF {\intMathMod{##1-2}{\intEval{#1 / #2}}} = {0} {
        % column descriptions
        \tlPutRight \lTmpaTl {Time & Callsign & RST tx & RST rx & Frequency/Name/Location/Notes\\}
      }{
        \intIncr \lTmpaInt
        % add empty rows with counter
        \tlPutRight \lTmpaTl {\hphantom{12345678} & \hphantom{AAA0AAA/AAA0AAA} & & & \SetCell[r=1,c=1]{r} \color{LightGray}}
        \tlPutRight \lTmpaTl {\intUse \lTmpaInt}
        \tlPutRight \lTmpaTl {\\}
      }
    }
  }
  \prgReturn {\expValue{\lTmpaTl}}
}


\begin{document}
\ttfamily
\SetTblrInner{rowsep=0pt,rulesep=0pt}
% two sides (front/back)
\foreach \i in {1,...,\numpages}
{
  \message{page \i}
  % watermark on every page
  \wmpagenumber
  \begin{center}
      % fix centering
    \addtolength{\leftskip} {-2cm}
    \addtolength{\rightskip}{-2cm}

    \begin{tblr}[evaluate=\makerows]{
        rows={\rowheight},
        width=\textwidth,
        vline{1-Y}={},
        hline{2-Z}={},
        colspec={YYYYZ Q[colsep=0pt]}
      }
      \makerows{\tablelines}{\numtables}
    \end{tblr}
  \end{center}
  \newpage
}
\end{document}
