#!/usr/bin/env bash
#
# Balinyaar secret-scanning pre-commit hook (refinement-phase-5).
# Blocks a commit that stages an obvious credential. This is a fast, dependency-free backstop for the
# root CLAUDE.md rule "Never commit secrets" — not a replacement for gitleaks/trufflehog in CI.
#
# Enable once per clone:   git config core.hooksPath .githooks
# Bypass a false positive:  git commit --no-verify   (use sparingly, and only when you are certain)
#
set -euo pipefail

# Committed placeholders are allowed — real values are not. Keep in sync with StartupSecretsGuard.
PLACEHOLDER='SET_VIA_USER_SECRETS_OR_ENV'

# Only scan added/changed lines in text files that are staged.
staged=$(git diff --cached --name-only --diff-filter=ACM)
[ -z "$staged" ] && exit 0

violations=0
report() { printf '  ✖ %s\n' "$1"; violations=$((violations + 1)); }

while IFS= read -r file; do
  # Skip this hook, lockfiles, and binaries.
  case "$file" in
    .githooks/*) continue ;;
    *.png|*.jpg|*.jpeg|*.gif|*.ico|*.pdf|*.dll|*.exe|*.snk) continue ;;
  esac
  [ -f "$file" ] || continue

  added=$(git diff --cached -U0 -- "$file" | grep '^+' | grep -v '^+++' || true)
  [ -z "$added" ] && continue

  # The historically-leaked SQL Server host — must never reappear.
  echo "$added" | grep -Eq '87\.107\.152\.16' && report "$file: leaked SQL Server host 87.107.152.16"

  # The retired hardcoded admin password.
  echo "$added" | grep -Eq 'qw123321' && report "$file: hardcoded admin password 'qw123321'"

  # A real (non-placeholder) connection-string password in a committed appsettings file.
  case "$file" in
    *appsettings*.json)
      echo "$added" \
        | grep -Ei 'Password=[^;"'"'"' ]+' \
        | grep -viq "Password=${PLACEHOLDER}" \
        && report "$file: connection-string password must be '${PLACEHOLDER}' (real value belongs in user-secrets/env)"
      ;;
  esac

  # Private keys and common cloud tokens, anywhere.
  echo "$added" | grep -Eq -- '-----BEGIN (RSA|EC|OPENSSH|PRIVATE) .*PRIVATE KEY-----' && report "$file: private key material"
  echo "$added" | grep -Eq 'AKIA[0-9A-Z]{16}' && report "$file: AWS access key id"
done <<< "$staged"

if [ "$violations" -gt 0 ]; then
  echo ""
  echo "Commit blocked: $violations potential secret(s) staged. Move the real value to user-secrets"
  echo "(Development) or an environment variable (deploy) and commit only the '${PLACEHOLDER}' placeholder."
  echo "See dev/post-phase/refinement/RUNBOOK.md. To override a false positive: git commit --no-verify"
  exit 1
fi

exit 0
