#!/bin/sh
set -e
last="$(
	find ~/work/invoices/*/ -name 'frisk-*.ods' -printf '%f\n' |
	sed 's/^frisk-//;s/\.ods$//' |
	sort -n |
	tail -n1
)"
if [ $# -eq 0 ] || [ "$1" = auto ] ; then
	f=$((last+1))
else
	f=$1
fi
if [ $# -eq 2 ] ; then
	day="$2"
	day="$(date -d "$day" +%F)"
else
	day="$(date +%F)"
fi
if [ "$(date -d "$day" +%m)" -ge 7 ] ; then
	tax_year="$(date -d "$day" +%Y)-$(($(date -d "$day" +%Y)+1))"
else
	tax_year="$(($(date -d "$day" +%Y)-1))-$(date -d "$day" +%Y)"
fi
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-frisk-invoice-"$f"
mkdir ~/tmp-frisk-invoice-"$f"
cd ~/tmp-frisk-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-frisk-invoice-"$f"
	exit
fi
mkdir --parents ~/work/invoices/"$tax_year"/
cd ~/work/invoices/"$tax_year"/
test -e frisk-"$f".ods || cp ../../frisk/legal/invoice.ods frisk-"$f".ods
cd ~/tmp-frisk-invoice-"$f"
textql -save-to timesheet.db -header -dlm tab timesheet.tsv
sqlite3 -csv timesheet.db \
	'.output timesheet.csv' \
	"SELECT 'Paul Wise Timesheet FE $day'" \
	'SELECT ""' \
	'SELECT "Date", "Hours", "Tickets"' \
	'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="frisk";' \
	'SELECT "TOTAL", CAST(SUM([duration minutes]) / 60 AS TEXT) || ":" || CAST(SUM([duration minutes]) % 60 AS TEXT) FROM timesheet WHERE category="frisk";'
rm -f timesheet.tsv timesheet.db
mv timesheet.csv frisk-paul-wise-timesheet-fe-"$day".csv
scite frisk-paul-wise-timesheet-fe-"$day".csv &
cd ~/work/invoices/"$tax_year"/
libreoffice frisk-"$f".ods
if cmp --quiet ../../frisk/legal/invoice.ods frisk-"$f".ods ; then
	rm -rf frisk-"$f".ods ~/tmp-frisk-invoice-"$f"
	exit 0
fi
libreoffice --headless --convert-to pdf --outdir ~/tmp-frisk-invoice-"$f" frisk-"$f".ods
cd ~/tmp-frisk-invoice-"$f"
mv frisk-"$f".pdf frisk-paul-wise-invoice-"$f".pdf
evince frisk-paul-wise-invoice-"$f".pdf
find . -type f -print0 |
sed --null-data i--attach |
xargs --null \
	xdg-email \
		--subject "Paul Wise invoice $f" \
		--body "Hi,\n\nLatest invoice and timesheet for the past two weeks." \
		--cc 'Cathy Daniels <cdaniels@frisk.com.au>' \
		--cc 'Cindy Halasz <chalasz@frisk.com.au>' \
		'Frisk Accounts <accounts@frisk.com.au>'
read -r _
cd
rm -rf ~/tmp-frisk-invoice-"$f"
