#!/bin/bash
#
# Pre-commit hook for DoD/MilSpec compliance
# Prevents committing secrets and credentials
#

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "Running pre-commit security checks..."

# Check for common secret patterns
SECRET_PATTERNS=(
    "password\s*=\s*['\"][^'\"]+['\"]"
    "secret\s*=\s*['\"][^'\"]+['\"]"
    "api[_-]?key\s*=\s*['\"][^'\"]+['\"]"
    "token\s*=\s*['\"][^'\"]+['\"]"
    "private[_-]?key\s*=\s*['\"][^'\"]+['\"]"
    "-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----"
    "-----BEGIN\s+CERTIFICATE-----"
    "AKIA[0-9A-Z]{16}"  # AWS Access Key ID
    "sk_live_[0-9a-zA-Z]{24,}"  # Stripe live key
    "xox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24,34}"  # Slack token
)

# Files to check (staged files)
FILES=$(git diff --cached --name-only --diff-filter=ACM)

FOUND_SECRETS=0

for file in $FILES; do
    # Skip binary files
    if git diff --cached --numstat "$file" | grep -q '^-'; then
        continue
    fi
    
    # Skip files in .gitignore patterns
    if git check-ignore -q "$file"; then
        continue
    fi
    
    # Check each pattern
    for pattern in "${SECRET_PATTERNS[@]}"; do
        if git diff --cached "$file" | grep -qiE "$pattern"; then
            echo -e "${RED}ERROR:${NC} Potential secret found in $file"
            echo -e "${YELLOW}Pattern:${NC} $pattern"
            FOUND_SECRETS=1
        fi
    done
    
    # Check for common insecure defaults
    if git diff --cached "$file" | grep -qiE "(your-secret-key-change-in-production|CHANGE_ME|TODO.*secret|FIXME.*password)"; then
        echo -e "${YELLOW}WARNING:${NC} Insecure default or placeholder found in $file"
        echo -e "${YELLOW}Please ensure this is not a real secret${NC}"
    fi
done

# Check for files that should never be committed
FORBIDDEN_FILES=(
    ".env"
    "*.key"
    "*.pem"
    "*.p12"
    "*.pfx"
    "secrets/"
    "credentials/"
)

for file in $FILES; do
    for forbidden in "${FORBIDDEN_FILES[@]}"; do
        if [[ "$file" == $forbidden ]] || [[ "$file" == *"$forbidden"* ]]; then
            echo -e "${RED}ERROR:${NC} Forbidden file type detected: $file"
            echo -e "${RED}Files matching $forbidden should never be committed${NC}"
            FOUND_SECRETS=1
        fi
    done
done

if [ $FOUND_SECRETS -eq 1 ]; then
    echo ""
    echo -e "${RED}Commit blocked due to potential security issues${NC}"
    echo -e "${YELLOW}If this is a false positive, you can bypass with:${NC}"
    echo -e "${YELLOW}  git commit --no-verify${NC}"
    echo -e "${YELLOW}(Use with extreme caution)${NC}"
    exit 1
fi

echo -e "${GREEN}Pre-commit security checks passed${NC}"
exit 0

