#!/usr/bin/env bash
# Scan staged changes for secrets before they enter history - the only cheap
# moment to stop them, since a committed secret lives in git history forever
# even after deletion. This hook is the sole automated gate; there is no CI
# backstop. Rules + verified-false-positive allowlist: .gitleaks.toml.
set -euo pipefail

if ! command -v gitleaks >/dev/null 2>&1; then
  echo "pre-commit: gitleaks not installed; SKIPPING the secret scan." >&2
  echo "  install: brew install gitleaks" >&2
  exit 0
fi

if ! gitleaks git --staged --no-banner --redact -v; then
  echo >&2
  echo "pre-commit: gitleaks flagged a staged secret (above)." >&2
  echo "  real secret?    unstage it, rotate the credential, then re-stage" >&2
  echo "  false positive? add a narrow allowlist block to .gitleaks.toml" >&2
  exit 1
fi

# Block a staged CHANGELOG.md whose top section uses non-canonical headers - the
# release body is that section verbatim and propagates to GitHub/homebrew/nix.
if git diff --cached --name-only | grep -qx 'CHANGELOG.md'; then
  if ! ops/scripts/check-changelog-headers.sh; then
    echo "pre-commit: CHANGELOG.md headers off-taxonomy (above); keep the emoji form." >&2
    exit 1
  fi
fi
