#!/bin/sh
# timesheet-invoice - Create an invoice from an org-mode timesheet
# Copyright (c) 2014 Informatique, Inc.
# Licensed under MIT http://opensource.org/licenses/MIT

set -e
cwd="$(pwd -P)"
program="$(basename $0)"
dir="$(dirname $0)"
cd "$dir"
dir="$(pwd -P)"
cd "$cwd"

# -- generic --

if [ -e "$dir/shell.funcs" ]; then
    . "$dir/shell.funcs"
else
    echo "E: $program could not find common functions $tests/shell.funcs"
    exit 1
fi

# -- program functions --

do_usage() {
    rv=$1
    cat >&2 <<EOF
Usage: ${program} [OPTIONS] ACTION
  OPTIONS
    -h --help	print usage information
    -d --debug
    -v --verbose
    -i --invoice--dir DIR	Set the invoice directory
  ACTIONS
    -c --check	check setup (default)
    -l --latex	Run LaTeX to create an invoice (does check)
    -p --pdf	View PDF invoice (does latex)

EOF
    exit $rv
}

preaction_debug() {
    log " "
    log "===== Starting $program $testname ====="
    log "program=$program"
    log "dir=$dir"
    log "debug=$debug"
    log "verbose=$verbose"
    log "invoice_dir=$invoice_dir"
    log "action=$action"
    for v in $*; do
        val=$(eval echo \$$v)
        log "$v=$val"
    done
    log " "
    return 0
}

# -- actions --

do_check() {
    rv=0
    vecho "--- check ---"
    if [ ! -d "$invoice_dir" ]; then
        err "invoice directory not found: $invoice_dir"
        rv=1
    else
        cd "$invoice_dir"
    fi
    if [ $rv -eq 0 ] && [ ! -e header.tsv ]; then
        err "file not found: header.tsv"
        rv=1
    fi
    if [ $rv -eq 0 ] && [ ! -e detail.tsv ]; then
        err "file not found: detail.tsv"
        rv=1
    fi
    if [ $rv -eq 0 ] && [ ! -e main.tex ]; then
        vecho "copying LaTeX invoice template"
        # share_dir="$(dirname $invoice_dir)/../../share"
        share_dir="$(dirname $invoice_dir)"
        share_dir="$(dirname $share_dir)"
        share_dir="$(dirname $share_dir)/share"
        vecho "share_dir=$share_dir"
        for f in defs.tex main.tex logo.pdf; do
            cp "$share_dir/$f" ./
        done
    fi
    return $rv
}

do_latex() {
    rv=0
    do_check
    rv=$?
    if [ $rv -eq 0 ]; then
        vecho "--- latex ---"
    fi
    # header.tsv -> header.tex
    header="header.tex"
    remitto1="$(echo $(tail -n +2 header.tsv | head -1 | cut -f1) | sed 's/#/\\\#/g')"
    billdate="$(tail -n +2 header.tsv | head -1 | cut -f2)"
    invoice="$(tail -n +2 header.tsv | head -1 | cut -f3)"
    # echo "company=$company="
    # echo "billdate=$billdate="
    # echo "invoice=$invoice="
    remitto2="$(echo $(tail -n +3 header.tsv | head -1 | cut -f1) | sed 's/#/\\\#/g')"
    remitto3="$(echo $(tail -n +4 header.tsv | head -1 | cut -f1) | sed 's/#/\\\#/g')"
    billto1="$(tail -n +6 header.tsv | head -1 | cut -f1)"
    terms="$(tail -n +6 header.tsv | head -1 | cut -f2)"
    duedate="$(tail -n +6 header.tsv | head -1 | cut -f3)"
    billto2="$(tail -n +7 header.tsv | head -1 | cut -f1)"
    billto3="$(tail -n +8 header.tsv | head -1 | cut -f1)"
    hours="$(tail -n +10 header.tsv | head -1 | cut -f1)"
    amount="$(tail -n +10 header.tsv | head -1 | cut -f2)"
    echo "%% $header" > $header.in
    b='\'
    printf "%sdef%sinvoice{$invoice}\n" $b $b >> $header.in
    printf "%sdef%sbilldate{$billdate}\n" $b $b >> $header.in
    printf "%sdef%sduedate{$duedate}\n" $b $b >> $header.in
    printf "%sdef%sterms{$terms}\n" $b $b >> $header.in
    printf "%sdef%shours{$hours}\n" $b $b >> $header.in
    printf "%sdef%samount{$amount}\n" $b $b >> $header.in
    printf "%sdef%sremittoA{$remitto1}\n" $b $b >> $header.in
    printf "%sdef%sremittoB{$remitto2}\n" $b $b >> $header.in
    printf "%sdef%sremittoC{$remitto3}\n" $b $b >> $header.in
    printf "%sdef%sbilltoA{$billto1}\n" $b $b >> $header.in
    printf "%sdef%sbilltoB{$billto2}\n" $b $b >> $header.in
    printf "%sdef%sbilltoC{$billto3}\n" $b $b >> $header.in
    sed -e 's/\$/\\$/g' -e 's/#/\\#/g' -e 's/£/\\pounds{}/g' -e 's/€/\\euro{}/g' $header.in > $header
    # detail.tsv -> detail.tex
    detail=detail.tex
    echo "%% $detail" > $detail.in
    n=$(wc -l detail.tsv | awk {'print $1'})
    i=2
    while [ $i -lt $n ]; do
        day="$(tail -n +$i detail.tsv | head -1 | cut -f1)"
        projects="$(tail -n +$i detail.tsv | head -1 | cut -f2)"
        hours="$(tail -n +$i detail.tsv | head -1 | cut -f3)"
        rate="$(tail -n +$i detail.tsv | head -1 | cut -f4)"
        subtotal="$(tail -n +$i detail.tsv | head -1 | cut -f5)"
        printf "%s & %s & %s & %s & %s %s%s %shline\n" "$day" "$projects" "$hours" "$rate"  "$subtotal" $b $b $b >> $detail.in
        i=$(($i + 1))
    done
    printf "%smulticolumn{2}{|r|}{%scellcolor[gray]{0.9} %s } &\n" $b $b $b >> $detail.in
    printf "%scellcolor[gray]{0.9} %shours &\n" $b $b >> $detail.in
    printf "%scellcolor[gray]{0.9} %stextbf{Total} &\n" $b $b >> $detail.in
    printf "%scellcolor[gray]{0.9} %stextbf{%samount} %s%s %shline\n" $b $b $b $b $b $b >> $detail.in
    printf "%sarrayrulecolor{white}\n" $b >> $detail.in
    sed -e 's/\$/\\$/g' -e 's/#/\\#/g' -e 's/£/\\pounds{}/g' -e 's/€/\\euro{}/g' $detail.in > $detail
    # run LaTeX
    texbase=main
    cd "$invoice_dir"
    rm -f $texbase.aux $texbase.log $texbase.out $texbase.pdf $texbase.rubbercache
    vecho "rubber --pdf $texbase.tex"
    if ! rubber --pdf $texbase.tex ; then
        err "error running LaTeX"
        rv=1
    fi
    pdf="Invoice-$invoice.pdf"
    if [ $rv -eq 0 ] && [ -f "$invoice_dir/$texbase.pdf" ]; then
        mv "$invoice_dir/$texbase.pdf" "./$pdf"
        echo "created $pdf"
        rm -rf "$tmpdir"
    else
        err "error creating $pdf"
        rv=1
    fi
    return $rv
}

do_pdf() {
    rv=0
    do_latex
    rv=$?
    if [ $rv -eq 0 ]; then
        vecho "--- view ---"
        if [ -e "$pdf" ]; then
            # must handle all streams so caller (emacs) can close
            evince "$pdf" < /dev/null > /dev/null 2>&1 &
        else
            err "cannot view file: $pdf"
            rv=1
        fi
    fi
    return $rv
}

# -- main --

debug=0
verbose=''
action='check'
invoice_dir=''
pdf=''
while test $# -ne 0; do
    case "$1" in
        -h|--help)
            do_usage 0
            ;;
        -d|--debug)
            debug=$((debug + 1))
            ;;
        -v|--verbose)
            verbose='--verbose'
            ;;
        -c|--check)
            action='check'
            ;;
        -l|--latex)
            action='latex'
            ;;
        -p|--pdf)
            action='pdf'
            ;;
        -i|--invoice-dir)
            if [ $# -gt 1 ]; then
                shift
                invoice_dir="$1"
            else
                err "missing argument for --invoice-dir"
                do_usage 1
            fi
            ;;
        *)
            err "no additional args may be specified"
            do_usage 1
            ;;
        *)
            # if [ -z "$testname" ]; then
            #     testname="$1"
            # else
                 err "no additional args may be specified"
                 do_usage 1
            # fi
            ;;
    esac
    shift
done

# insure an action has been specified
[ "$#" -eq 0 ] || do_usage 1
[ -n "$action" ] || do_usage 1

# required environment variable list
evars="TEXINPUTS"
verify_vars $evars

[ $debug -eq 0 ] || preaction_debug $evars

# do the action
do_$action
