#!/usr/bin/env bash
# migr pre-commit hook

# Halt immediately on any error, including those hidden within pipelines
set -eo pipefail

# Does anything staged affect the build or the suite? If not, skip both to save
# time. tests/stubs/* and tests/fuzz/corpus/* are matched by path rather than
# extension on purpose: stubs shadow real command names on PATH, and a corpus
# input's name is its expected outcome, so neither can carry one.
if ! git diff --cached --name-only | grep -qE '\.(c|h|sh)$|(^|/)Makefile$|^tests/stubs/|^tests/fuzz/corpus/'; then
    echo "→ Nothing staged that the build or tests depend on, skipping both."
    exit 0
fi

# Every gate runs on exactly what is staged, in a copy: unstaged edits can
# neither hide a failure nor cause one, and the working tree's build stays.
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
git checkout-index --all --prefix="$work/"

echo "▶ Running every gate on the staged tree (this takes several minutes)..."

if ! make -C "$work" check > /tmp/migr-check.log 2>&1; then
    echo "× A gate failed. See /tmp/migr-check.log for details."
    exit 1
fi

echo "✓ All checks passed!"
exit 0
