#!/usr/bin/env bash
# Client-side hook: scan staged files with secret_scan.py, then run unit tests.
# This is advice. `git commit --no-verify` and `git -c core.hooksPath=...` skip it.
# Git does not record whether this hook ran.
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
SCAN="$ROOT/tools/secret_scan.py"
if [[ ! -f "$SCAN" ]]; then
  echo "pre-commit: missing tools/secret_scan.py" >&2
  exit 1
fi
# Staged files only (Added / Copied / Modified). Deleted paths are skipped.
mapfile -t STAGED < <(git diff --cached --name-only --diff-filter=ACM)
if ((${#STAGED[@]})); then
  python3 "$SCAN" "$ROOT" --paths "${STAGED[@]}"
else
  echo "pre-commit: no staged files to scan"
fi
# Cheap unit tests so a hook failure can also come from a broken test,
# not only from a secret. Agents under pressure skip this the same way.
if [[ -d "$ROOT/tests" ]]; then
  python3 -m pytest -q "$ROOT/tests" || exit 1
fi
# Marker written only when the hook actually ran to completion.
# A pre-push hook can require a fresh marker. An agent can still
# skip pre-push with --no-verify, so this is not a merge gate.
mkdir -p "$ROOT/.git"
date -u +"%Y-%m-%dT%H:%M:%SZ" > "$ROOT/.git/hook-ok"
echo "pre-commit: ok (wrote .git/hook-ok)"
