#!/usr/bin/env bash
# Is this binary trustworthy as gate evidence?
#
#   verify-build-identity.sh <binary-commit>
#
# Two independent facts, both established HERE at launch rather than trusted
# from inside the binary:
#
#   1. the stamped commit equals the checkout's real HEAD
#   2. the migration crates have no uncommitted changes
#
# A compiled-in cleanliness flag cannot do this: cargo will not re-run a build
# script because another crate's source changed, so it can read "clean" for a
# binary built from edited sources. Verified on the Blaze host.
#
# REFUSES (exit non-zero) rather than warning. For a migration gate a warning on
# stderr is not a safeguard — it is something to scroll past.
set -uo pipefail
cd "$(dirname "$(readlink -f "$0")")/.."

STAMPED="${1:-}"
[[ -n "$STAMPED" ]] || { echo "usage: verify-build-identity.sh <binary-commit>" >&2; exit 2; }

# Reject anything that is not a commit BEFORE comparing. Passing the binary
# path instead of its stamp otherwise produces a perfectly plausible-looking
# REFUSING line, which reads as a real finding rather than a caller mistake —
# and a safeguard that cries wolf is one people learn to work around.
if [[ ! "$STAMPED" =~ ^[0-9a-f]{7,40}$ ]]; then
  echo "usage error: expected a commit hash, got '$STAMPED'" >&2
  echo "  (to check a binary: verify-build-identity.sh \"\$(BIN --identity | sed -nE 's/.*commit=([0-9a-f]+).*/\\1/p')\")" >&2
  exit 2
fi

CRATES=(openfut-protocol-blaze openfut-adapter-fifa17 openfut-host-config
        openfut-blaze-host openfut-redirector-host)

rc=0
HEAD_NOW="$(git rev-parse --short=7 HEAD 2>/dev/null || echo unknown)"

if [[ "$STAMPED" != "$HEAD_NOW" ]]; then
  echo "REFUSING: binary was built from $STAMPED but HEAD is $HEAD_NOW" >&2
  echo "  Rebuild before treating this run as evidence." >&2
  rc=1
fi

DIRT="$(git status --porcelain --untracked-files=no -- "${CRATES[@]}" 2>/dev/null)"
if [[ -n "$DIRT" ]]; then
  echo "REFUSING: migration crates have uncommitted changes:" >&2
  sed 's/^/  /' <<<"$DIRT" >&2
  rc=1
fi

if [[ $rc -eq 0 ]]; then
  echo "build identity OK: commit $STAMPED == HEAD, migration crates clean"
fi
exit $rc
