#!/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"

# 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."
