~ecs/dotfiles

32338bcde141a54436179b0393fa30cddafce6e9 — Eyal Sawady 22 days ago 295b8fe
bin/report: implement weekly summaries
1 files changed, 53 insertions(+), 27 deletions(-)

M bin/report
M bin/report => bin/report +53 -27
@@ 1,32 1,58 @@
#!/bin/sh -eu

# TODO: Print a summary of hours by week on 0 args

printf "%s %s out\n" "$(date +%s)" "$(date)" | cat "$XDG_DATA_HOME/clock" - \
	| awk -v"start=$(date -d"${1:-7am last monday}" +%s)" -v"end=$(date -d"${2:-7am this monday}" +%s)" '
	BEGIN {
		state = "out";
		seconds = 0;
		prev = 0;
	}
	/in$/ {
		if (state == "out" && $1 >= start) {
			prev = $1;
report() {
	printf "%s %s out\n" "$(date +%s)" "$(date)" | cat "$XDG_DATA_HOME/clock" - \
			| awk -v"start=$(date -d"$1" +%s)" -v"end=$(date -d"$2" +%s)" '
		BEGIN {
			state = "out";
			seconds = 0;
			prev = 0;
		}
		/in$/ {
			if (state == "out" && $1 >= start) {
				prev = $1;
			}
			state = "in"
		}
		state = "in"
	}
	/out$/ {
		if (state == "in" && prev != 0 && prev <= end) {
			if ($1 > end) {
				seconds += end - prev;
			} else {
				seconds += $1 - prev;
		/out$/ {
			if (state == "in" && prev != 0 && prev <= end) {
				if ($1 > end) {
					seconds += end - prev;
				} else {
					seconds += $1 - prev;
				}
			}
			state = "out";
		}
		state = "out";
	}
	END {
		printf("%.0f:%02d:%02d\n",
			seconds / 3600, (seconds % 3600) / 60, seconds % 60)
	}
'
		END {
			printf("%.0f:%02d:%02d\n",
				seconds / 3600, (seconds % 3600) / 60, seconds % 60)
		}
	'
}

ts() {
	date -ud"@$1" +%Y-%m-%dT%H:%M:%SZ
}

case $# in
	0)
		report "7am last monday" "7am this monday"
		;;
	1)
		end="$(date -ud "12pm last monday" +%s)"
		start="$((end - 604800 * ($1 - 1)))"
		for t in $(seq "$start" 604800 "$end"); do
			printf "%s - %s: " "$(ts "$t")" "$(ts "$((t + 604800))")"
			report "@$t" "@$((t + 604800))"
		done
		;;
	2)
		report "$1" "$2"
		;;
	*) 
		printf "usage: %s\n" "$0"
		printf "usage: %s <weeks>\n" "$0"
		printf "usage: %s <start> <end>\n" "$0"
		;;
esac