#!/bin/sh

TIMEFILE="$HOME/timekeeping.csv"

usage () {
    >&2 printf "usage:\n\t%s <start|pause|end>" "$(basename "$0")"
    exit 0
}

die () {
    >&2 echo "Error: $*"
    exit 1
}

from_ts () {
    if ! date --version >/dev/null 2>&1; then # BSD
        date -r "$1" '+%H:%M'
    else # GNU
        date -d "@$1" '+%H:%M'
    fi
}

pause_end () {
    if [ "$ACTION" = "pause" ]; then
        now="$(date '+%s')"
        printf "%s," "$((now - START))" >> "$TIMEFILE"
        >&2 printf "\nYou took a %d minutes pause\n" "$(( (now - START) / 60))"
    fi
}

trap pause_end INT

test -z "$1" && usage
test -e "$TIMEFILE" || touch "$TIMEFILE"

TODAY="$(date '+%Y-%m-%d')"
START="$(date '+%s')"
ACTION="$1"


case "$1" in
    start)
        grep -qE "^$TODAY" "$TIMEFILE" && die "you already started your day"
        printf "%s,%s," "$TODAY" "$(date '+%s')" >> "$TIMEFILE"
        >&2 printf "Started work at %s\n" "$(date '+%H:%M')";;
    pause)
        grep -qE "^$TODAY" "$TIMEFILE" || die "You haven't even started your day!"
        awk -F, "/^$TODAY/"'{if (NF > 4) exit 1}' "$TIMEFILE" || die "You're already done for the day"
        awk -F, "/^$TODAY/"'{if (NF > 2) exit 1}' "$TIMEFILE" || die "You've already expanded your daily break allowance"
        >&2 echo "Taking a break..."
        sleep 9999999;;
    end)
        test -z "$2" && die "Tell me what you did today"
        grep -qE "^$TODAY" "$TIMEFILE" || die "You haven't even started your day!"
        start_hour="$(from_ts "$(tail -n1 "$TIMEFILE" | cut -f 2 -d ,)")"
        end_hour="$(date '+%H:%M')"
        shift 1
        msg="$(printf "%s" "$*" | sed 's/"/""/g')"
        line="$(awk -F ',' -v now="$START" -v start="$start_hour" -v end="$end_hour" -v msg="$msg" \
            "/^$TODAY/"'{
                    total=now-$2-$3;
                    h=int(total/3600);
                    m=int(total/60%60);
                    ph=int($3/3600);
                    pm=int($3/60%60);
                    printf "%s,%s,%s,%s:%s,%s:%s,\"%s\"",$1,start,end,ph,pm,h,m,msg;
                }' \
                    "$TIMEFILE")"
       printf "\$d\nw\n\q" | ed "$TIMEFILE" > /dev/null 2>&1
       printf "%s\n" "$line" >> "$TIMEFILE";;
esac