#!/bin/bash
#
# 🔒 ROA2WEB Security Setup Script
# Complete security implementation for the ROA2WEB project
#

set -e

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

echo -e "${GREEN}"
echo "=============================================="
echo "🔒 ROA2WEB SECURITY IMPLEMENTATION SETUP"
echo "=============================================="
echo -e "${NC}"

# Function to print step headers
print_step() {
    echo -e "${BLUE}📋 Step $1: $2${NC}"
    echo "----------------------------------------"
}

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check prerequisites
print_step "1" "Checking Prerequisites"

if ! command_exists python3; then
    echo -e "${RED}❌ Python 3 is required but not installed${NC}"
    exit 1
fi

if ! command_exists git; then
    echo -e "${RED}❌ Git is required but not installed${NC}"
    exit 1
fi

if [[ ! -d ".git" ]]; then
    echo -e "${RED}❌ Not in a git repository${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Prerequisites check passed${NC}"
echo

# Install git hooks
print_step "2" "Installing Git Security Hooks"

if [[ -f "security/install_hooks.sh" ]]; then
    chmod +x security/install_hooks.sh
    ./security/install_hooks.sh
else
    echo -e "${RED}❌ Hook installer not found${NC}"
    exit 1
fi
echo

# Make scripts executable
print_step "3" "Setting Script Permissions"

chmod +x security/secrets_scanner.py
chmod +x security/git_cleanup.py

echo -e "${GREEN}✅ Script permissions set${NC}"
echo

# Run initial security scan
print_step "4" "Running Initial Security Scan"

echo -e "${YELLOW}🔍 Scanning repository for secrets...${NC}"
python3 security/secrets_scanner.py --save-report initial_security_scan.json

echo

# Check git history for secrets
print_step "5" "Checking Git History"

echo -e "${YELLOW}🕐 Scanning git history (this may take a moment)...${NC}"
python3 security/secrets_scanner.py --scan-git-history --save-report git_history_scan.json

echo

# Verify .gitignore protection
print_step "6" "Verifying .gitignore Protection"

echo "🔍 Checking .gitignore coverage..."

# Check if critical patterns are in .gitignore
critical_patterns=(
    "*.env"
    "*.key"
    "*.pem"
    "*secret*"
    "*credential*"
    "*password*"
)

gitignore_issues=0
for pattern in "${critical_patterns[@]}"; do
    if ! grep -q "$pattern" .gitignore; then
        echo -e "${YELLOW}⚠️  Pattern '$pattern' not found in .gitignore${NC}"
        gitignore_issues=$((gitignore_issues + 1))
    fi
done

if [[ $gitignore_issues -eq 0 ]]; then
    echo -e "${GREEN}✅ .gitignore security patterns verified${NC}"
else
    echo -e "${YELLOW}⚠️  $gitignore_issues security patterns missing from .gitignore${NC}"
fi

echo

# Create security monitoring cron job (optional)
print_step "7" "Setting Up Security Monitoring (Optional)"

echo "📅 Would you like to set up automated daily security scans?"
echo "This will add a cron job to run security scans daily at 9 AM"
read -p "Setup automated scans? (y/N): " setup_cron

if [[ "$setup_cron" =~ ^[Yy]$ ]]; then
    # Get current directory
    current_dir=$(pwd)
    
    # Create cron job entry
    cron_entry="0 9 * * * cd $current_dir && python3 security/secrets_scanner.py --save-report daily_scan_\$(date +\\%Y\\%m\\%d).json >/dev/null 2>&1"
    
    # Add to crontab
    (crontab -l 2>/dev/null; echo "$cron_entry") | crontab -
    
    echo -e "${GREEN}✅ Daily security scan cron job added${NC}"
else
    echo "📝 Skipped automated scan setup"
fi

echo

# Security setup summary
print_step "8" "Security Setup Summary"

echo -e "${GREEN}🎉 ROA2WEB Security Implementation Complete!${NC}"
echo
echo "📋 What was installed:"
echo "  ✅ Git hooks (pre-commit, commit-msg)"
echo "  ✅ Secrets scanner tool"
echo "  ✅ Git history cleanup tool"
echo "  ✅ Enhanced .gitignore patterns"
echo "  ✅ Security documentation"
echo
echo "📊 Security scan results:"
echo "  📄 Initial scan: initial_security_scan.json"
echo "  📄 History scan: git_history_scan.json"
echo
echo "🔧 Available tools:"
echo "  🔍 Security scan: python3 security/secrets_scanner.py"
echo "  🧹 Git cleanup: python3 security/git_cleanup.py"
echo "  📋 Documentation: security/README.md"
echo

# Critical warnings
if [[ -f "initial_security_scan.json" ]]; then
    critical_violations=$(python3 -c "
import json
try:
    with open('initial_security_scan.json', 'r') as f:
        data = json.load(f)
    print(data.get('summary', {}).get('critical_violations', 0))
except:
    print(0)
" 2>/dev/null || echo "0")

    if [[ "$critical_violations" -gt 0 ]]; then
        echo -e "${RED}"
        echo "🚨 CRITICAL SECURITY ALERT!"
        echo "=============================="
        echo -e "${NC}"
        echo -e "${RED}Found $critical_violations critical security violations!${NC}"
        echo
        echo "🔧 IMMEDIATE ACTIONS REQUIRED:"
        echo "1. 🔑 Regenerate all exposed credentials"
        echo "2. 🧹 Clean git history: python3 security/git_cleanup.py --cleanup"
        echo "3. 🚀 Force push cleaned history to all remotes"
        echo "4. 📢 Notify team to re-clone repository"
        echo
        echo "📖 See security/README.md for detailed procedures"
        echo
    fi
fi

echo -e "${BLUE}📚 Next Steps:${NC}"
echo "1. Review security scan reports"
echo "2. Read security/README.md for detailed guidance"
echo "3. Follow security/SECURITY_PROCEDURES.md for ongoing security"
echo "4. Train team members on new security procedures"
echo
echo -e "${GREEN}🔒 ROA2WEB is now security-enhanced!${NC}"