#!/usr/bin/env bash
# Git pre-commit hook: same checks for every tool and every person.
# Enable once per clone:  git config core.hooksPath .githooks
set -u
fail=0
staged="$(git diff --cached --name-only --diff-filter=ACM)"

# 1) secrets files must never be committed
while IFS= read -r f; do
  [ -z "$f" ] && continue
  b="$(basename "$f")"
  case "$b" in *.example|*.sample|*.template) continue ;; esac
  case "$b" in
    .env|.env.*|*.pem|*.key|*.p12|id_rsa*|id_ed25519*|credentials.json) echo "pre-commit: secrets file staged: $f" >&2; fail=1 ;;
  esac
  case "$f" in secrets/*|*/secrets/*) echo "pre-commit: file in secrets/ staged: $f" >&2; fail=1 ;; esac
done <<< "$staged"

# 2) obvious keys in staged content (use gitleaks if installed)
if command -v gitleaks >/dev/null 2>&1; then
  gitleaks protect --staged --no-banner >/dev/null 2>&1 || { echo "pre-commit: gitleaks found a possible secret" >&2; fail=1; }
elif git diff --cached -U0 | grep -E '^\+' | grep -Eq '(sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,}|xox[baprs]-[A-Za-z0-9-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)'; then
  echo "pre-commit: staged changes look like they contain an API key or private key" >&2; fail=1
fi

# 3) project done-check
if [ -x .harness/done.sh ]; then
  .harness/done.sh >/dev/null 2>/tmp/harness-done.$$ || { echo "pre-commit: .harness/done.sh failed:" >&2; tail -n 30 /tmp/harness-done.$$ >&2; fail=1; }
  rm -f /tmp/harness-done.$$
fi

[ $fail -eq 0 ] || { echo "Commit blocked. Fix the above (or, if you are sure, the human can use --no-verify)." >&2; exit 1; }
