#!/usr/bin/env bash
# Pre-commit hook: scan staged changes for leaked secrets, tokens, and API keys with gitleaks

set -e

# Resolve gitleaks executable
if command -v gitleaks &> /dev/null; then
  GITLEAKS_BIN="gitleaks"
elif [ -x "/opt/homebrew/bin/gitleaks" ]; then
  GITLEAKS_BIN="/opt/homebrew/bin/gitleaks"
elif [ -x "/usr/local/bin/gitleaks" ]; then
  GITLEAKS_BIN="/usr/local/bin/gitleaks"
else
  echo "⚠️  [gitleaks-hook] Warning: 'gitleaks' executable not found on PATH."
  echo "   Please install it to prevent committing credentials: brew install gitleaks"
  echo "   Skipping secret check for this commit."
  exit 0
fi

echo "🔍 [gitleaks-hook] Scanning staged changes for secrets..."

# Run gitleaks protect on staged changes
if ! "$GITLEAKS_BIN" protect --staged -v; then
  echo ""
  echo "❌ [gitleaks-hook] Commit rejected: Potential secret or credential leak detected!"
  echo "   Please remove any sensitive keys, tokens, or passwords before committing."
  echo "   If this is a false positive and you are certain it is safe, bypass with: git commit --no-verify"
  echo ""
  exit 1
fi

echo "✅ [gitleaks-hook] No leaked secrets detected in staged files."
exit 0
