#!/usr/bin/env bash
set -euo pipefail

# Check staged files for plain Kubernetes Secrets
ERRORS=0

while IFS= read -r -d '' file; do
  # Skip if file doesn't exist (e.g., deleted files)
  [[ -f "$file" ]] || continue

  # Check if the file contains a plain Kubernetes Secret
  if grep -q "^kind: Secret" "$file"; then
    # Explicit opt-out for public-data bootstrap secrets (e.g. the CA bundle
    # that establishes Vault trust and therefore cannot be Vault-sourced).
    if grep -q "^# pre-commit: allow-plain-secret" "$file"; then
      continue
    fi
    # Allow secure secret types
    if ! grep -q -E "^kind: (SealedSecret|ExternalSecret|VaultStaticSecret|VaultDynamicSecret)" "$file"; then
      echo "BLOCKED: $file contains a plain Kubernetes Secret" >&2
      echo "  Use VaultStaticSecret or VaultDynamicSecret instead" >&2
      ((ERRORS++))
    fi
  fi
done < <(git diff --cached --name-only --diff-filter=ACM -z | grep -zE '\.(yaml|yml)$')

exit $ERRORS
