#!/usr/bin/env bash
# Installed via `git config core.hooksPath tools/hooks` (tools/install_hooks.sh). Runs:
#   1. tools/check_no_rom.sh     IP-safety scan of tracked files
#   2. the index/worktree match: see "What the gate builds" below
#   3. make check                byte-identical round trip (ROM SHA-1 + SPC700 driver),
#                                only when staged changes can affect the build
#   (the lockstep gates are a release checklist, not a hook: see README.md "Releasing")
#                                script can reach, and
#                                frame-line parity, when staged changes touch recomp/
#                                or config/assets.txt
#   6. tools/progress.py         refresh docs/PROGRESS.md and docs/progress.json,
#                                and stage them into this commit
# Bypass with --no-verify only for commits that cannot touch the build; the pre-push
# hook re-runs the gate on the pushed tip regardless.
#
# --- What the gate builds ----------------------------------------------------
# `make check` and `make recomp-check` build the *working tree*. The thing being
# committed is the *index*. When those differ, a commit can pass the gate and still
# not rebuild: stage half an edit to tools/names.txt with `git add -p`, the whole edit
# is on disk, the build is byte-identical, and the committed tree is not.
#
# Three ways to close that:
#   (a) refuse the commit while the index and the working tree differ under any path
#       the gate reads, so building the working tree *is* building the commit;
#   (b) `git stash push --keep-index` around the build;
#   (c) export the index into a temporary `git worktree` and build there.
# (b) is rejected: a stash that fails to pop (a merge conflict, an interrupted hook,
# a build that kills the shell) leaves the user's uncommitted work somewhere they did
# not put it, and a hook must never be able to lose work. (c) is rejected: the build
# needs baserom/DREAM.sfc, tools/bin/asar and data/, all of them ignored and none of
# them in the index, so the temporary tree has to be stitched back to the real one by
# hand, and the stitching is exactly where a stale data/ would hide.
# (a) is what runs below. It cannot lose work and it has no partial state. The cost is
# that a partial commit of a build-sensitive path is refused rather than verified;
# commit the whole edit, or use --no-verify and let the pre-push hook be the gate.
# Untracked files under those paths are refused for the same reason: an `incsrc` of a
# file that is not in the commit builds here and nowhere else.
set -e
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
tools/check_no_rom.sh

STAGED=$(git diff --cached --name-only -z | tr '\0' '\n')
BUILD_SENSITIVE=$(grep -E '^(src/|spc/|tools/|config/|Makefile$)' <<<"$STAGED" || true)
RECOMP_TOUCHED=$(grep -E '^(recomp/|config/recomp|tools/recomp_verify\.py$)' <<<"$STAGED" || true)
APP_TOUCHED=$(grep -E '^(recomp/|config/assets\.txt$)' <<<"$STAGED" || true)
if [[ -z "$BUILD_SENSITIVE" && -z "$RECOMP_TOUCHED" && -z "$APP_TOUCHED" ]]; then
    exit 0
fi

# The paths the gates about to run will read.
GATE_PATHS=()
[[ -n "$BUILD_SENSITIVE" ]] && GATE_PATHS+=(src spc tools config Makefile)
[[ -n "$RECOMP_TOUCHED" || -n "$APP_TOUCHED" ]] && GATE_PATHS+=(recomp tools config)
DIRTY=$(git diff --name-only -- "${GATE_PATHS[@]}")
UNTRACKED=$(git ls-files -o --exclude-standard -- "${GATE_PATHS[@]}")
if [[ -n "$DIRTY" || -n "$UNTRACKED" ]]; then
    echo "pre-commit: the working tree is not the tree being committed, so the gate" >&2
    echo "            below would verify content this commit does not carry." >&2
    [[ -n "$DIRTY" ]]     && { echo "  staged and working copies differ:" >&2; sed 's/^/    /' <<<"$DIRTY" >&2; }
    [[ -n "$UNTRACKED" ]] && { echo "  untracked, so not in the commit:" >&2; sed 's/^/    /' <<<"$UNTRACKED" >&2; }
    echo "            Stage the rest (git add), stash it, or remove it, then commit again." >&2
    exit 1
fi

if [[ ! -f baserom/DREAM.sfc ]]; then
    echo "pre-commit: baserom/DREAM.sfc missing: cannot run the SHA-1 gate, skipping" >&2
    exit 0
fi
if [[ ! -x tools/bin/asar ]]; then
    echo "pre-commit: tools/bin/asar missing: build asar first (see README), skipping gate" >&2
    exit 0
fi
if [[ -n "$BUILD_SENSITIVE" ]]; then
    echo "pre-commit: make check (SHA-1 gate) ..."
    if ! make -s check; then
        echo "pre-commit: BUILD FAILED: the staged changes break the byte-identical round trip." >&2
        exit 1
    fi
fi
# The lockstep gates (make recomp-check, recomp-check-units, recomp-check-nocpu, app-check)
# are not run here: they take about 25 minutes. They are the release checklist in
# README.md ("Releasing") and are run by hand before a tag.

echo "pre-commit: refreshing progress ..."
python3 tools/progress.py >/dev/null
git add docs/PROGRESS.md docs/progress.json
