#!/bin/sh
#
# Pre-commit hook for Diamond
#
# This script runs multiple checks:
# 1. Gitleaks - Ensures no secrets are committed (test fixtures allowlisted in .gitleaks.toml)
# 2. Author check - Prevents commits authored by test users from entering repo history

FAILED=0

# Check 1: Gitleaks protection
command -v gitleaks >/dev/null 2>&1 || {
    echo "Error: gitleaks is not installed or not in the PATH."
    echo "Please install it (e.g., 'brew install gitleaks') to commit changes."
    exit 1
}

echo "Running gitleaks protection..."
gitleaks protect --staged --redact --verbose

if [ $? -eq 0 ]; then
    echo "✓ Gitleaks check passed."
else
    echo "
    ______________________________________________________________________
   /                                                                      \\
  |  GITLEAKS DETECTED SECRETS!                                          |
  |                                                                      |
  |  Your commit has been blocked because it contains potential secrets. |
  |  Please remove the secrets and stage the changes again.              |
  |                                                                      |
  |  If this is a false positive (e.g., test fixtures), add an           |
  |  allowlist entry to .gitleaks.toml                                   |
   \\______________________________________________________________________/
    "
    FAILED=1
fi

# Check 2: Prevent commits authored by test users (from unit test accidents)
AUTHOR_NAME=$(git config user.name)
AUTHOR_EMAIL=$(git config user.email)

if echo "$AUTHOR_NAME" | grep -qi "test user" || echo "$AUTHOR_EMAIL" | grep -qi "test@example.com"; then
    echo ""
    echo "❌ Error: Git author is set to a test user"
    echo ""
    echo "   Author: $AUTHOR_NAME <$AUTHOR_EMAIL>"
    echo ""
    echo "   This looks like your git config was set by test code."
    echo "   Please reset your git config:"
    echo ""
    echo "   git config user.name \"Your Name\""
    echo "   git config user.email \"your@email.com\""
    echo ""
    FAILED=1
fi

# Check 3: Run personal pre-commit checks if they exist
# Developers can add their own checks in .git/hooks/pre-commit.local (not tracked)
if [ -f .git/hooks/pre-commit.local ]; then
    .git/hooks/pre-commit.local
    if [ $? -ne 0 ]; then
        FAILED=1
    fi
fi

exit $FAILED
