#!/bin/sh
if [ $# -eq 0 ] ; then
        last="$(
                find ~/work/invoices/*/ -name 'freie-*.ods' -printf '%f\n' |
                sed 's/^freie-//;s/\.ods$//' |
                sort -n |
                tail -n1
        )"
        f=$((last+1))
else
	f=$1
fi
if [ "$(date +%m)" -ge 7 ] ; then
	tax_year="$(date +%Y)-$(($(date +%Y)+1))"
else
	tax_year="$(($(date +%Y)-1))-$(date +%Y)"
fi
day="$(date +%F)"
day="$(date -d "$day -$(date -d "$day" +%w) days" +%F)"
w1e="$(date -d "$day -$(date -d "$day" +%u) days" +%F)"
w1s="$(date -d "$w1e -$(($(date -d "$w1e" +%u)-1)) days" +%F)"
w2e="$day"
rm -rf ~/tmp-freie-invoice-"$f"
mkdir ~/tmp-freie-invoice-"$f"
cd ~/tmp-freie-invoice-"$f"
hamster export tsv "$w1s" "$w2e" > timesheet.tsv
if [ $( < timesheet.tsv tail -n +2 | head -n -1 | wc -l) -le 0 ] ; then
	rm -rf ~/tmp-freie-invoice-"$f"
	exit
fi
mkdir --parents ~/work/invoices/"$tax_year"/
cd ~/work/invoices/"$tax_year"/
test -e freie-"$f".ods || cp ../../freie/legal/invoice.ods freie-"$f".ods
cd ~/tmp-freie-invoice-"$f"
textql -save-to timesheet.db -header -dlm tab timesheet.tsv
sqlite3 -csv timesheet.db \
	'.output timesheet.csv' \
	"SELECT 'Paul Wise Timesheet for invoice #$f'" \
	'SELECT ""' \
	'SELECT "Date", "Hours", "Activity"' \
	'SELECT substr([start time], 1, instr([start time]," ")-1), CAST([duration minutes]/60 AS TEXT) || ":" || CAST([duration minutes] % 60 AS TEXT), activity || ": " || description FROM timesheet WHERE category="freie";' \
	'SELECT "TOTAL", CAST(SUM([duration minutes]) / 60 AS TEXT) || ":" || CAST(SUM([duration minutes]) % 60 AS TEXT) FROM timesheet WHERE category="freie";'
rm -f timesheet.tsv timesheet.db
mv timesheet.csv freie-paul-wise-timesheet-"$f".csv
scite freie-paul-wise-timesheet-"$f".csv &
cd ~/work/invoices/"$tax_year"/
libreoffice freie-"$f".ods
libreoffice --headless --convert-to pdf --outdir ~/tmp-freie-invoice-"$f" freie-"$f".ods
cd ~/tmp-freie-invoice-"$f"
mv freie-"$f".pdf freie-paul-wise-invoice-"$f".pdf
evince freie-paul-wise-invoice-"$f".pdf
find -type f -print0 | sed --null-data i--attach | xargs --null xdg-email --subject "Paul Wise to Fre(i)e Software GmbH: invoice #$f" --body "Hi,\n\nLatest invoice and timesheet for recent software development work." 'Mike Gabriel <mike.gabriel@das-netzwerkteam.de>'
read foo
cd
rm -rf ~/tmp-freie-invoice-"$f"
