#!/bin/bash
#
# 🔒 ROA2WEB Pre-commit Hook
# Prevents committing files with secrets and credentials
#
# Installation:
#   cp security/git_hooks/pre-commit .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 -e "${GREEN}🔒 ROA2WEB Security Pre-commit Check${NC}"

# Critical patterns to detect
CRITICAL_PATTERNS=(
    "ORACLE_PASSWORD"
    "ROMFASTSOFT"
    "Parola81"
    "VALID_USERS.*password"
    "-----BEGIN.*PRIVATE KEY-----"
    "AKIA[0-9A-Z]{16}"  # AWS Access Key
    "Bearer [A-Za-z0-9\-\._~\+\/]+=*"  # Bearer tokens
)

# Suspicious file patterns
SUSPICIOUS_FILES=(
    "\.env$"
    "_rsa$"
    "\.pem$"
    "\.key$"
    "secret"
    "credential"
    "password"
    "config\.prod"
)

# Function to check if file should be scanned
should_scan_file() {
    local file="$1"
    
    # Skip deleted files
    if [[ ! -f "$file" ]]; then
        return 1
    fi
    
    # Skip binary files
    if file "$file" | grep -q binary; then
        return 1
    fi
    
    # Skip safe extensions
    case "$file" in
        *.png|*.jpg|*.jpeg|*.gif|*.pdf|*.zip|*.tar.gz|*.ico) return 1 ;;
    esac
    
    return 0
}

# Function to scan file content for secrets
scan_file_content() {
    local file="$1"
    local violations=0
    
    for pattern in "${CRITICAL_PATTERNS[@]}"; do
        if grep -qiE "$pattern" "$file" 2>/dev/null; then
            echo -e "${RED}❌ CRITICAL: Secret pattern detected in $file${NC}"
            echo -e "${YELLOW}   Pattern: $pattern${NC}"
            grep -inE "$pattern" "$file" | head -3 | while read line; do
                echo -e "${YELLOW}   $line${NC}"
            done
            violations=$((violations + 1))
        fi
    done
    
    return $violations
}

# Function to check suspicious filenames
check_suspicious_filename() {
    local file="$1"
    
    for pattern in "${SUSPICIOUS_FILES[@]}"; do
        if echo "$file" | grep -qiE "$pattern"; then
            # Allow .env.example files
            if echo "$file" | grep -q "\.example$"; then
                continue
            fi
            
            echo -e "${RED}❌ SUSPICIOUS: Potentially sensitive file: $file${NC}"
            echo -e "${YELLOW}   Pattern: $pattern${NC}"
            return 1
        fi
    done
    
    return 0
}

# Get list of staged files
staged_files=$(git diff --cached --name-only --diff-filter=ACM)

if [[ -z "$staged_files" ]]; then
    echo -e "${GREEN}✅ No staged files to check${NC}"
    exit 0
fi

echo "🔍 Scanning staged files for secrets..."

total_violations=0
scanned_files=0

# Check each staged file
while IFS= read -r file; do
    if should_scan_file "$file"; then
        scanned_files=$((scanned_files + 1))
        
        # Check filename
        if ! check_suspicious_filename "$file"; then
            total_violations=$((total_violations + 1))
        fi
        
        # Check content
        scan_file_content "$file"
        violations=$?
        total_violations=$((total_violations + violations))
    fi
done <<< "$staged_files"

echo "📊 Scanned $scanned_files files"

# Check if any violations found
if [[ $total_violations -gt 0 ]]; then
    echo -e "${RED}"
    echo "=========================================="
    echo "🚨 COMMIT BLOCKED - SECURITY VIOLATIONS!"
    echo "=========================================="
    echo -e "${NC}"
    echo "Found $total_violations security violations"
    echo ""
    echo "🔧 Actions to take:"
    echo "1. Remove sensitive data from files"
    echo "2. Move secrets to environment variables"
    echo "3. Add files to .gitignore if needed"
    echo "4. Regenerate any exposed credentials"
    echo ""
    echo "ℹ️  To bypass this check (NOT RECOMMENDED):"
    echo "   git commit --no-verify"
    echo ""
    exit 1
fi

echo -e "${GREEN}✅ Security check passed - no violations found${NC}"
exit 0