#!/usr/bin/env bash
# smoke-pre-commit.sh  -  verify pre-commit-check.sh catches all secret patterns.
# Uses a real temp git repo to test the actual hook behavior end-to-end.
# No mocks, no test-only flags  -  tests exactly what runs in production.

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
HOOK="$SCRIPT_DIR/pre-commit-check.sh"

if [ ! -f "$HOOK" ]; then
  echo "FAIL: pre-commit-check.sh not found at $HOOK" >&2
  exit 1
fi

PASS=0
FAIL=0

pass() { PASS=$((PASS+1)); echo "  ✓ $1"; }
fail() { FAIL=$((FAIL+1)); echo "  ✗ $1"; }

TMPDIR=$(mktemp -d) || { echo "FAIL: mktemp" >&2; exit 1; }
trap 'rm -rf "$TMPDIR"' EXIT

# Bootstrap a real git repo with an initial commit
git -C "$TMPDIR" init -q
git -C "$TMPDIR" config user.email "test@test.com"
git -C "$TMPDIR" config user.name "Test"
echo "init" > "$TMPDIR/init.txt"
git -C "$TMPDIR" add init.txt
git -C "$TMPDIR" commit -q -m "init"

# Stage a file with content and run the hook inside the temp repo
stage_and_check() {
  local filename="$1" content="$2"
  echo "$content" > "$TMPDIR/$filename"
  git -C "$TMPDIR" add "$filename"
}

reset_stage() {
  git -C "$TMPDIR" reset -q HEAD -- . 2>/dev/null
  git -C "$TMPDIR" checkout -q -- . 2>/dev/null
  rm -f "$TMPDIR"/test-* "$TMPDIR"/.env* 2>/dev/null
}

run_hook() {
  (cd "$TMPDIR" && bash "$HOOK") >/dev/null 2>&1
  return $?
}

check_detects() {
  local desc="$1" filename="$2" content="$3"
  reset_stage
  stage_and_check "$filename" "$content"
  if run_hook; then
    fail "$desc (hook passed, expected block)"
  else
    pass "$desc"
  fi
}

check_passes() {
  local desc="$1" filename="$2" content="$3"
  reset_stage
  stage_and_check "$filename" "$content"
  if run_hook; then
    pass "$desc"
  else
    fail "$desc (hook blocked, expected pass)"
  fi
}

echo "→ 1. Secret pattern detection"

check_detects "API key (api_key=long_string)" \
  "test-file.swift" \
  'let api_key = "ghp_aBcDeFgHiJkLmNoPqRsT1234567890"'

check_detects "AWS access key (AKIA prefix)" \
  "test-file.py" \
  'aws_key = "AKIAIOSFODNN7EXAMPLE"'

check_detects "RSA private key header" \
  "test-file.pem" \
  '-----BEGIN RSA PRIVATE KEY-----'

check_detects "Generic private key header" \
  "test-file.key" \
  '-----BEGIN PRIVATE KEY-----'

check_detects "EC private key header" \
  "test-file.key" \
  '-----BEGIN EC PRIVATE KEY-----'

check_detects "GCP service account JSON" \
  "test-file.json" \
  '{"type": "service_account", "project_id": "my-project"}'

check_detects "GitHub PAT (ghp_ 36 chars)" \
  "test-file.txt" \
  'token: ghp_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789'

check_detects "Slack token (xoxb-)" \
  "test-file.txt" \
  'slack = "xoxb-123456789012-abcdefghijklmnop"'

check_detects "Google API key (AIza)" \
  "test-file.txt" \
  'gmaps = "AIzaSyA1234567890abcdefghijklmnopqrstuv"'

check_detects "JWT three-segment token" \
  "test-file.txt" \
  'auth = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N"'

check_detects "High-entropy custom secret (no known prefix)" \
  "test-file.txt" \
  'session = "Zx9Kq2Lm7Pw4Nv8Rt3Yb6Hc1Df5Gj0Sa2Wd7Qe4Uo9Ik"'

check_detects "Secret in a filename WITH SPACES (no false-negative)" \
  "test secret file.txt" \
  'token: ghp_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789'

echo ""
echo "→ 2. File-name based detection"

check_detects ".env file blocked by name" \
  ".env" \
  "DATABASE_URL=postgres://localhost/db"

check_detects ".env.local blocked by name" \
  ".env.local" \
  "SECRET=foo"

check_detects "Credentials JSON blocked by name" \
  "credentials.json" \
  '{"user": "admin"}'

echo ""
echo "→ 3. Clean files pass"

check_passes "Normal Swift code" \
  "test-file.swift" \
  'import Foundation
let greeting = "Hello, World!"
func add(_ a: Int, _ b: Int) -> Int { a + b }'

check_passes "Empty file" \
  "test-file.txt" \
  ""

check_passes "Git SHA / hex hash is not flagged as high-entropy" \
  "test-file.txt" \
  'commit a1b2c3d4e5f6789012345678901234567890abcd resolved'

check_passes "Lockfile integrity hash is exempt" \
  "test-yarn.lock" \
  'resolved "https://r.npm/x" integrity sha512-Zx9Kq2Lm7Pw4Nv8Rt3Yb6Hc1Df5Gj0Sa2Wd7Qe4Uo9IkLp=='

echo ""
echo "→ 4. No staged files = clean exit"
reset_stage
if run_hook; then
  pass "No staged files exits 0"
else
  fail "No staged files exits 0"
fi

echo ""
echo "══ pre-commit smoke: $PASS passed, $FAIL failed ══"
[ "$FAIL" -eq 0 ]
