#!/bin/bash
# rustfmt gate: blocks a commit whose staged Rust files are not formatted.
#
# Activate in a fresh clone (one-time):
#   git config core.hooksPath scripts/githooks
#
# Bypass for a work-in-progress commit: git commit --no-verify
#
# Only crates with staged .rs changes are checked, so the hook stays fast on a
# large repo. Each file maps to the nearest enclosing Cargo.toml, and the check
# runs as `cargo fmt` there, which picks up that crate's edition and any
# rustfmt.toml rather than guessing.
set -euo pipefail

ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

# --- secret scan (gitleaks) -------------------------------------------------
# Independent guardrail: blocks a commit whose staged changes contain a secret,
# regardless of whether a human judged the value "safe". Shared ruleset lives at
# ~/Code/.gitleaks.toml. Degrades gracefully if gitleaks is not installed (the
# astra pre-receive hook is the backstop that always runs). Task: infra 97ffeda0.
if command -v gitleaks >/dev/null 2>&1; then
    GL_CFG=""
    if [ -f "$ROOT/.gitleaks.toml" ]; then
        GL_CFG="$ROOT/.gitleaks.toml"
    elif [ -f "$HOME/Code/.gitleaks.toml" ]; then
        GL_CFG="$HOME/Code/.gitleaks.toml"
    fi
    gl_args=(git --staged --no-banner --redact)
    [ -n "$GL_CFG" ] && gl_args+=(-c "$GL_CFG")
    if ! gitleaks "${gl_args[@]}"; then
        echo "pre-commit: gitleaks found a secret in the staged changes."
        echo "            remove it (or allowlist a false positive), then restage."
        echo "            bypass: git commit --no-verify."
        exit 1
    fi
    echo "pre-commit: gitleaks clean."
else
    echo "pre-commit: gitleaks not installed; skipping secret scan (astra gates on push)."
fi

# --- migration immutability -------------------------------------------------
# sqlx checksums a migration's whole file when it runs it and refuses one whose
# bytes changed since. So editing a migration that has already been applied
# anywhere breaks every deploy against that database with "previously applied
# but modified" — for a comment edit, and for a line-ending change, exactly as
# much as for a schema change.
#
# The 2026-07-27 exorcise sweep rewrote comments in 29 applied migrations and
# converted one from CRLF to LF. Nothing in the test suite checksums a
# migration, so it stayed invisible while it blocked every server deploy for
# three days. Hence a gate at commit time: a migration that already exists in
# HEAD may not be modified, renamed, or deleted. Adding a new one is always fine.
touched="$(git diff --cached --name-only --diff-filter=MDR -- '*migrations/*.sql')"
if [ -n "$touched" ]; then
    echo "pre-commit: these already-committed migrations were modified, renamed, or deleted:"
    while IFS= read -r m; do
        [ -n "$m" ] && echo "              $m"
    done <<< "$touched"
    echo "            A migration is immutable once applied; sqlx checksums the whole"
    echo "            file, comments included. Write a new migration instead."
    echo "            Bypass ONLY if it has never been applied anywhere, including"
    echo "            prod, staging, and your dev database: git commit --no-verify."
    exit 1
fi
echo "pre-commit: migrations unmodified."

# --- openapi.json staleness -------------------------------------------------
# server/openapi.json is a committed artifact and `openapi::tests::
# committed_spec_matches_generated` asserts it matches the generated spec. The
# spec embeds CARGO_PKG_VERSION, so EVERY version bump invalidates it even when
# no route changed.
#
# Nothing local caught that. The /deploy pre-push guard is a `cargo test
# --no-run` compile check, and the spec is read at runtime by path rather than
# include_str!, so a stale copy compiles fine. On 2026-08-06 the v0.11.8 bump
# left the spec at 0.11.7, pushed clean to all three remotes, and killed Sando
# run 38 about fifteen minutes in — two full remote build cycles for a one-line
# diff in info.version.
#
# So: regenerate to stdout and compare against the STAGED copy (not the working
# tree one — regenerating without restaging is the same bug wearing a hat).
specish="$(git diff --cached --name-only --diff-filter=ACMR \
    -- 'server/Cargo.toml' 'server/src/*.rs' 'server/src/**/*.rs' 'server/openapi.json')"
if [ -n "$specish" ]; then
    echo "pre-commit: checking openapi.json against the generated spec..."
    gen="$(mktemp)"
    trap 'rm -f "$gen"' EXIT
    if (cd "$ROOT/server" && cargo run --quiet --bin export-openapi -- --stdout) > "$gen" 2>/dev/null; then
        if ! git show :server/openapi.json 2>/dev/null | diff -q - "$gen" >/dev/null; then
            echo "pre-commit: server/openapi.json is stale (or regenerated but not staged)."
            echo "            cd server && cargo run --bin export-openapi"
            echo "            git add server/openapi.json"
            echo "            Then vendor the same bytes into the OTHER repo, which this"
            echo "            commit cannot carry and Sando will fail on:"
            echo "              cp server/openapi.json ../synckit/synckit-client/tests/openapi.json"
            echo "            Bypass: git commit --no-verify."
            exit 1
        fi
        echo "pre-commit: openapi.json current."
    else
        echo "pre-commit: could not build export-openapi; skipping spec check."
        echo "            cargo_test in Sando is the backstop, 15 minutes into the build."
    fi
fi

# Paths the gate ignores (extended regex, matched against repo-relative paths).
# Empty means check everything.
SKIP_PATHS="${SKIP_PATHS:-}"

staged="$(git diff --cached --name-only --diff-filter=ACMR -- '*.rs')"
if [ -n "$SKIP_PATHS" ]; then
    staged="$(printf '%s\n' "$staged" | grep -Ev "$SKIP_PATHS" || true)"
fi
[ -n "$staged" ] || exit 0

# Map each staged file to the directory of its nearest Cargo.toml.
crates=""
while IFS= read -r f; do
    [ -n "$f" ] || continue
    d="$(dirname "$f")"
    while [ "$d" != "." ] && [ ! -f "$d/Cargo.toml" ]; do
        d="$(dirname "$d")"
    done
    [ -f "$d/Cargo.toml" ] || continue
    crates="$crates$d"$'\n'
done <<< "$staged"

crates="$(printf '%s' "$crates" | sort -u)"
[ -n "$crates" ] || exit 0

failed=0
while IFS= read -r c; do
    [ -n "$c" ] || continue
    if ! (cd "$c" && cargo fmt --check >/dev/null 2>&1); then
        echo "pre-commit: rustfmt gate failed in $c"
        failed=1
    fi
done <<< "$crates"

if [ "$failed" -ne 0 ]; then
    echo "pre-commit: run 'cargo fmt' in the crates above, then restage."
    echo "pre-commit: commit aborted (use --no-verify to bypass)."
    exit 1
fi

echo "pre-commit: rustfmt gate clean."
