#!/usr/bin/env bash
#
# Fails when frontend/bindings/ is stale against the bound Go services.
#
# frontend/bindings/ is generated by `wails3`, not by `go generate`, so
# the pre-commit codegen check does not cover it at all.  Without this, a
# renamed Go struct field or a changed method signature first shows up at
# runtime, inside a window, as a binding that never settles.
#
# v3's generator is a static analyser rather than a build-and-run of the
# app, which is what makes this cheap enough to gate a commit on — and
# also what makes the build tags matter.  It sees only the configuration
# it is told about; the one that matters is the one users run, which is
# the default tag set (GTK4 + WebKitGTK 6.0).  The other two
# configurations this repo builds — `indexbuild` and `dev` — add no bound
# service, so generating under them would only widen the surface past
# what ships.

set -euo pipefail

cd "$(dirname "$0")/.."

TARGET="frontend/bindings"

# Only *unstaged* work is in the way.  Generating overwrites the working
# tree, so an unstaged edit here would be destroyed; a staged one is
# precisely what this is being asked about, and rejecting it made the
# hook unsatisfiable — every bindings change is staged by the time the
# commit that carries it runs this.
if ! git diff --quiet -- "$TARGET"; then
	echo "bindings-check: $TARGET has unstaged changes; stage or stash them first" >&2
	git status --short -- "$TARGET" >&2
	exit 1
fi

go tool wails3 generate bindings -clean=true -ts -i >/dev/null 2>&1

if ! git diff --quiet -- "$TARGET"; then
	echo "bindings-check: $TARGET is out of date with the Go bindings." >&2
	echo "Run 'make bindings' and stage the result." >&2
	git diff --stat -- "$TARGET" >&2
	exit 1
fi

# A *new* file is a new service or a rename, which a diff of tracked
# paths cannot see.  (A deleted one it can: the diff above compares the
# working tree against the index, where the file still is.)
if [ -n "$(git ls-files --others --exclude-standard -- "$TARGET")" ]; then
	echo "bindings-check: $TARGET gained files." >&2
	git ls-files --others --exclude-standard -- "$TARGET" >&2
	exit 1
fi

echo "bindings-check: frontend/bindings is current"
