# Shared by the hooks: is a commit dated in UTC, and making HEAD so.

# True when REV's committer date is UTC, and its author date too when
# the author is us
utc_dated() {
	case "$(git log -1 --format=%ci "$1")" in *+0000) ;; *) return 1 ;; esac
	[ "$(git log -1 --format=%ae "$1")" = "$(git config user.email)" ] || return 0
	case "$(git log -1 --format=%ai "$1")" in *+0000) return 0 ;; esac
	return 1
}

# Mid rebase or cherry-pick a commit can't be amended (git refuses)
utc_sequencing() {
	for f in rebase-merge rebase-apply CHERRY_PICK_HEAD sequencer REVERT_HEAD; do
		[ -e "$(git rev-parse --git-path $f)" ] && return 0
	done
	return 1
}

utc_fix_head() {
	utc_dated HEAD && return 0
	# A rebase --exec step may amend; a pick can't. Our own re-stamp's
	# picks stay quiet: its exec step comes right after each.
	if [ -z "$C8_UTC_EXEC" ] && utc_sequencing; then
		[ -n "$C8_UTC_RESTAMP" ] ||
			echo "post-commit: git can't amend mid ${2:-rebase or" \
				"cherry-pick}, so this one is in local time: run" \
				".githooks/utc-restamp BASE when it's done (or TZ=UTC git ...)" >&2
		return 0
	fi
	if [ "$(git log -1 --format=%ae)" = "$(git config user.email)" ]; then
		TZ=UTC git commit -q --amend --no-edit --no-verify --allow-empty \
			--date="@$(git log -1 --format=%at) +0000"
	else
		TZ=UTC git commit -q --amend --no-edit --no-verify --allow-empty
	fi
}

# Re-stamp everything after BASE (a commit, or --root)
utc_restamp() {
	hooks=$(cd "$(dirname "$0")" && pwd)
	C8_UTC_RESTAMP=1 TZ=UTC git rebase -q --force-rebase --rebase-merges \
		--exec "C8_UTC_EXEC=1 sh -c '. \"$hooks/utc.sh\"; utc_fix_head'" "$1"
}
