#!/usr/bin/env bash
# pre-commit hook — block a commit whose MANIFEST sha256 hashes have drifted
# from the working tree. Ensures every release ships a MANIFEST whose published
# hashes match the bytes being pushed, so the auto-updater's local-skip logic
# (larry.sh sync_from_manifest) never compares against a stale hash.
#
# Install:  scripts/make-manifest.sh --install-hook
#
# The hook is intentionally NON-FATAL when sha256 tooling is unavailable on the
# committer's box (it can't verify, so it warns and allows) — the same fail-safe
# philosophy the client uses. It only BLOCKS when it can prove drift.

root="$(git rev-parse --show-toplevel 2>/dev/null)" || exit 0
gen="$root/scripts/make-manifest.sh"
[ -x "$gen" ] || exit 0   # generator absent (older checkout) — don't block

# Only enforce when MANIFEST or a manifested file is part of this commit, to
# avoid hashing on every unrelated commit. Cheap heuristic: always check; the
# generator is fast.
out="$("$gen" --check 2>&1)"; rc=$?
case "$rc" in
  0) exit 0 ;;
  1)
    echo "" >&2
    echo "pre-commit: MANIFEST hashes are out of date." >&2
    echo "$out" >&2
    echo "" >&2
    echo "Fix: run  scripts/make-manifest.sh  then  git add MANIFEST  and re-commit." >&2
    exit 1
    ;;
  2|*)
    # Generation error (e.g. no sha256 tool on this box). Can't verify -> warn,
    # but don't block the commit. CI / the release box still enforces.
    echo "pre-commit: WARN — could not verify MANIFEST hashes ($out). Allowing commit." >&2
    exit 0
    ;;
esac
