#!/usr/bin/env bash
#
# Scans tracked files for common secret patterns.
# Intended for manual use (or as part of quick-check). Avoids printing matching lines.
#
# Note: This does not scan git history. Use a dedicated tool (e.g. gitleaks) for history scanning.

set -euo pipefail

ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "${ROOT}" ]]; then
  exit 0
fi

cd "${ROOT}"

fail=0

check() {
  local name="$1"
  local pattern="$2"

  # -l prints only filenames (no secret material in output)
  if git grep -l -E "${pattern}" -- . >/dev/null 2>&1; then
    echo "✗ ${name}: potential matches found in:"
    git grep -l -E "${pattern}" -- . | sed 's/^/  - /'
    echo
    fail=1
  fi
}

check "Private key blocks" '-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----'
check "Azure storage AccountKey leaks" 'AccountKey=[A-Za-z0-9+/=_-]{20,}'
check "Azure SharedAccessKey leaks" 'SharedAccessKey=[A-Za-z0-9+/=_-]{20,}'
check "COSMOS_KEY assignment leaks" 'COSMOS_KEY[[:space:]]*=[[:space:]]*[A-Za-z0-9+/=_-]{20,}'
check "AZURE_OPENAI_KEY assignment leaks" 'AZURE_OPENAI_KEY[[:space:]]*=[[:space:]]*[A-Za-z0-9+/=_-]{20,}'
check "AZURE_SPEECH_KEY assignment leaks" 'AZURE_SPEECH_KEY[[:space:]]*=[[:space:]]*[A-Za-z0-9+/=_-]{20,}'
check "JWT_SECRET hex-like assignments" 'JWT_SECRET[[:space:]]*=[[:space:]]*[0-9a-fA-F]{32,}'
check "OpenAI API keys (sk-...)" 'sk-[A-Za-z0-9]{20,}'
check "Stripe secret keys (sk_live_/sk_test_)" 'sk_(live|test)_[A-Za-z0-9]{20,}'
check "Stripe webhook secrets (whsec_...)" 'whsec_[A-Za-z0-9]{20,}'
check "Perplexity API keys (pplx-...)" 'pplx-[A-Za-z0-9]{20,}'
check "AWS access key ids (AKIA...)" 'AKIA[0-9A-Z]{16}'
check "Google API keys (AIza...)" 'AIza[0-9A-Za-z\-_]{35}'

if [[ "${fail}" -ne 0 ]]; then
  echo "Secret scan failed."
  echo "Fix the files above (move values to Key Vault / env vars) and retry."
  exit 1
fi

echo "✓ Secret scan passed (tracked files)"
