#!/usr/bin/env bash
# check-secrets.sh — Scan staged files for secrets and sensitive patterns
# Called by lefthook pre-commit and /commit command.
# Exit 0 = clean, Exit 1 = secrets found.
set -euo pipefail

STAGED_FILES=$(git diff --cached --name-only 2>/dev/null || true)
if [ -z "$STAGED_FILES" ]; then
  echo "No staged files to scan."
  exit 0
fi

# Check for secret files that must never be committed
SECRET_FILES=$(echo "$STAGED_FILES" | grep -E '\.env$|\.env\.|secrets\.|credentials\.|\.pem$|\.key$|id_rsa|id_ed25519|\.p12$|\.pfx$' || true)
if [ -n "$SECRET_FILES" ]; then
  echo "SECRETS FOUND — sensitive files staged:"
  echo "$SECRET_FILES" | sed 's/^/  /'
  echo ""
  echo "Remove with: git reset HEAD <file>"
  exit 1
fi

# Scan staged content for secret patterns
PATTERNS=(
  'sk-[a-zA-Z0-9]{32,}'              # OpenAI / Anthropic API keys
  'ghp_[a-zA-Z0-9]+'                 # GitHub personal access tokens
  'AKIA[A-Z0-9]{16}'                 # AWS access key IDs
  'password\s*=\s*["'"'"'][^"'"'"']{4,}'  # Hardcoded passwords
  'AIza[0-9A-Za-z_-]{35}'            # Google API keys
  'xox[bprsao]-[0-9a-zA-Z-]+'        # Slack tokens
  'GITHUB_TOKEN=['"'"'"][^'"'"'"]{4,}'  # GitHub token assignments
  'npm_[A-Za-z0-9]{36}'              # npm tokens
  'pypi-[A-Za-z0-9]{36,}'            # PyPI tokens
  '-----BEGIN [A-Z]+ PRIVATE KEY-----'  # Private keys (RSA, EC, etc.)
  'Bearer [a-zA-Z0-9_.~+/=-]{20,}'   # Bearer tokens
  'SG\.[a-zA-Z0-9_-]{22}\.[a-zA-Z0-9_-]{43}'  # SendGrid API keys
  'rk_live_[a-zA-Z0-9]{24,}'         # Stripe restricted keys
  'sk_live_[a-zA-Z0-9]{24,}'         # Stripe secret keys
)

# Build combined regex
COMBINED=$(printf '%s|' "${PATTERNS[@]}")
COMBINED="${COMBINED%|}"  # Remove trailing pipe

MATCHES=$(git diff --cached | grep -E "($COMBINED)" || true)
if [ -n "$MATCHES" ]; then
  echo "SECRETS FOUND — sensitive patterns in staged content:"
  echo "$MATCHES" | head -20
  if [ "$(echo "$MATCHES" | wc -l)" -gt 20 ]; then
    echo "  ... and more (showing first 20 matches)"
  fi
  echo ""
  echo "Review and remove secrets before committing."
  exit 1
fi

echo "Secret scan: clean"
exit 0
