#!/bin/bash
# ========================================
# Pre-commit Hook for PezkuwiChain
# ========================================
# This hook prevents committing sensitive data
#
# INSTALLATION:
# cp .git-hooks/pre-commit.example .git/hooks/pre-commit
# chmod +x .git/hooks/pre-commit

set -e

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

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

# ========================================
# 1. CHECK FOR .ENV FILES
# ========================================
echo "Checking for .env files..."

if git diff --cached --name-only | grep -E "^\.env$"; then
    echo -e "${RED}L ERROR: Attempting to commit .env file!${NC}"
    echo -e "${YELLOW}The .env file contains sensitive data and should never be committed.${NC}"
    echo ""
    echo "To fix this:"
    echo "  git reset HEAD .env"
    echo "  git add .env.example  # Commit the example file instead"
    exit 1
fi

if git diff --cached --name-only | grep -E "^\.env\.(local|production|staging)$"; then
    echo -e "${RED}L ERROR: Attempting to commit environment-specific .env file!${NC}"
    exit 1
fi

# ========================================
# 2. CHECK FOR SENSITIVE PATTERNS
# ========================================
echo "Scanning for sensitive patterns..."

# Patterns to search for
PATTERNS=(
    "password\s*=\s*['\"][^'\"]*['\"]"
    "api[_-]?key\s*=\s*['\"][^'\"]*['\"]"
    "secret\s*=\s*['\"][^'\"]*['\"]"
    "token\s*=\s*['\"][^'\"]*['\"]"
    "private[_-]?key"
    "BEGIN RSA PRIVATE KEY"
    "BEGIN PRIVATE KEY"
    "aws_secret_access_key"
    "AKIA[0-9A-Z]{16}"
)

FOUND_SECRETS=false

for pattern in "${PATTERNS[@]}"; do
    if git diff --cached | grep -iE "$pattern" > /dev/null; then
        if [ "$FOUND_SECRETS" = false ]; then
            echo -e "${RED}L ERROR: Potential secrets detected in staged files!${NC}"
            FOUND_SECRETS=true
        fi
        echo -e "${YELLOW}Found pattern: $pattern${NC}"
    fi
done

if [ "$FOUND_SECRETS" = true ]; then
    echo ""
    echo -e "${YELLOW}Detected patterns that might contain secrets.${NC}"
    echo "Please review your changes and ensure no sensitive data is being committed."
    echo ""
    echo "To bypass this check (NOT RECOMMENDED):"
    echo "  git commit --no-verify"
    exit 1
fi

# ========================================
# 3. CHECK FOR COMMON SECRET FILES
# ========================================
echo "Checking for secret files..."

SECRET_FILES=(
    "*.key"
    "*.pem"
    "*.cert"
    "*.p12"
    "*.pfx"
    "*secret*"
    "*credential*"
    ".npmrc"
    ".dockercfg"
    ".docker/config.json"
)

for file_pattern in "${SECRET_FILES[@]}"; do
    if git diff --cached --name-only | grep -i "$file_pattern" > /dev/null; then
        echo -e "${RED}L ERROR: Attempting to commit secret file matching: $file_pattern${NC}"
        echo "These files should be added to .gitignore"
        exit 1
    fi
done

# ========================================
# 4. CHECK FOR LARGE FILES
# ========================================
echo "Checking for large files..."

# Maximum file size in KB
MAX_FILE_SIZE=500

while IFS= read -r file; do
    if [ -f "$file" ]; then
        file_size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null)
        file_size_kb=$((file_size / 1024))

        if [ "$file_size_kb" -gt "$MAX_FILE_SIZE" ]; then
            echo -e "${YELLOW}   WARNING: Large file detected: $file (${file_size_kb}KB)${NC}"
            echo "Consider using Git LFS for large files"
        fi
    fi
done < <(git diff --cached --name-only)

# ========================================
# 5. CHECK FOR DEBUG CODE
# ========================================
echo "Checking for debug code..."

DEBUG_PATTERNS=(
    "console\.log"
    "debugger"
    "TODO.*security"
    "FIXME.*security"
    "XXX.*security"
)

for pattern in "${DEBUG_PATTERNS[@]}"; do
    if git diff --cached | grep -E "$pattern" > /dev/null; then
        echo -e "${YELLOW}   WARNING: Found debug code: $pattern${NC}"
        echo "Consider removing debug code before committing"
    fi
done

# ========================================
# 6. VERIFY ENVIRONMENT VARIABLES USAGE
# ========================================
echo "Checking environment variable usage..."

# Check for direct credential usage instead of env vars
if git diff --cached | grep -E "(password|api[_-]?key|secret).*['\"][^'\"]{20,}['\"]" > /dev/null; then
    echo -e "${YELLOW}   WARNING: Potential hardcoded credentials detected${NC}"
    echo "Please use environment variables instead:"
    echo "  import.meta.env.VITE_API_KEY"
fi

# ========================================
# 7. CHECK SPECIFIC FILES
# ========================================
echo "Checking specific configuration files..."

# Check if AuthContext has hardcoded credentials
if git diff --cached -- "src/contexts/AuthContext.tsx" | grep -E "password.*:" | grep -vE "import\.meta\.env" > /dev/null; then
    echo -e "${RED}L ERROR: AuthContext.tsx may contain hardcoded credentials${NC}"
    echo "Ensure all credentials use environment variables"
    exit 1
fi

# ========================================
# SUCCESS
# ========================================
echo -e "${GREEN} All security checks passed!${NC}"
echo ""

exit 0
