#!/bin/sh

BEAN_FILE=${BEAN_FILE:-~/.ledger/main.beancount}

if [ $# -lt 1 ] ; then
    echo "$(basename $0) YEAR" >&2
    exit 1
fi

YEAR=$1
FN="report-${YEAR}.tex"

DIVIDENDS_QUERY=$(printf 'select account, sum(position) as total_dividends where account ~ "Income:.*:Dividends" and year = %s group by account' $YEAR)
CAPITAL_GAINS_QUERY=$(printf 'select account, sum(position) as total_cap_gains where account ~ "Income:.*:CapGains" and year = %s group by account' $YEAR)
OTHER_INCOME_QUERY=$(printf 'select account, sum(position) as total_income where account ~ "Income:.*" and not account ~ "Dividends" and not account ~ "CapGains" and not account ~ "Unrealized" and year = %s group by account' $YEAR)

cat <<EOF >"${FN}"
\documentclass[paper=letter,DIV=14]{scrartcl}
\usepackage{booktabs,amsmath,dcolumn}
\newcolumntype{d}[1]{D{.}{\thinspace\mathbf{.}\thinspace}{#1} }

\title{Tax-related Reports for $YEAR}
\author{}
\date{}

\begin{document}

\maketitle
\tableofcontents
\newpage

EOF

cat <<EOF >>"${FN}"
\addsec{Income: General}

\begin{tabular}{ld{5}}
\toprule
\textbf{Type} & \multicolumn{1}{r}{\textbf{Amount (USD)}} \\\\
\midrule
EOF
bean-query -f csv ~/.ledger/main.beancount "${OTHER_INCOME_QUERY}" | \
    awk 'NR>1' | \
    sed -e 's/\r//' | \
    sed -e 's/ USD//' | \
    sed -e 's/Income://' | \
    awk --field-separator=, '{printf "%s & %s\n", $1, $2}' | \
    awk -e '{print $0"\\\\"}'>> "${FN}"
cat <<EOF >>"${FN}"
\bottomrule
\end{tabular}

EOF
    
cat <<EOF >>"${FN}"
\addsec{Income: Dividends}

\begin{tabular}{ld{5}}
\toprule
\textbf{Type} & \multicolumn{1}{r}{\textbf{Amount (USD)}} \\\\
\midrule
EOF
bean-query -f csv ~/.ledger/main.beancount "${DIVIDENDS_QUERY}" | \
    awk 'NR>1' | \
    sed -e 's/\r//' | \
    sed -e 's/ USD//' | \
    sed -e 's/Income://' | \
    awk --field-separator=, '{printf "%s & %s\n", $1, $2}' | \
    awk -e '{print $0"\\\\"}'>> "${FN}"
cat <<EOF >>"${FN}"
\bottomrule
\end{tabular}

EOF

cat <<EOF >>"${FN}"
\addsec{Income: Capital Gains}

\begin{tabular}{ld{5}}
\toprule
\textbf{Type} & \multicolumn{1}{r}{\textbf{Amount (USD)}} \\\\
\midrule
EOF
bean-query -f csv ~/.ledger/main.beancount "${CAPITAL_GAINS_QUERY}" | \
    awk 'NR>1' | \
    sed -e 's/\r//' | \
    sed -e 's/ USD//' | \
    sed -e 's/Income://' | \
    awk --field-separator=, -e '{printf "%s & %s\n", $1, $2}' | \
    awk -e '{print $0"\\\\"}'>> "${FN}"
cat <<EOF >>"${FN}"
\bottomrule
\end{tabular}

EOF


cat <<EOF >>"${FN}"
\end{document}
EOF

latexmk -pdf "${FN}"
latexmk -c "${FN}"
