#!/usr/bin/env bash
set -ueo pipefail
if [[ $# == 0 || "$1" == 'show' ]]; then
	exec git tree --show-notes --decorate=short --color=always \
		| grep -v '^|\s*$' \
		| grep -v 'Notes:$' \
		| sed 's/    Built-on: /^ Built-on: /' \
		| less
elif [[ "$1" == 'mark-built' ]] && (( $# >= 3 )) ; then
	commit=$2; hostname=$3; how=$4; shift 4; extra="$@"
	git fetch origin refs/notes/commits:refs/notes/commits
	if ! grep -Eqx 'how=(raw|make|nix)' <<<$how; then
		echo 'how must be one of: raw, make, nix' >/dev/stderr
		exit 1
	fi
	msg="Built-on: $hostname $how $extra"
	if grep -Fqx "$msg" <(git notes show "$commit" 2>/dev/null); then
		echo "$commit is already marked with '$msg'" >/dev/stderr
		exit
	fi
	git notes append -m "$msg" "$commit"
	git push origin refs/notes/commits
else
	echo 'Usage: ' >/dev/stderr
	echo '  helpers/notes [show]' >/dev/stderr
	echo -n '  helpers/notes mark-built ' >/dev/stderr
	echo '<commit> <hostname> how=[raw|make|nix] <extra stuff>' >/dev/stderr
	exit 1
fi
