#!/bin/bash

# Master Security Test Suite Runner
# Runs all security audits and generates comprehensive report

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPORT_FILE="security-report-$(date +%Y%m%d-%H%M%S).md"
LOG_FILE="security-test-$(date +%Y%m%d-%H%M%S).log"

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

echo -e "${BOLD}======================================"
echo "Global Gala Security Test Suite"
echo "======================================${NC}"
echo "Testing API: dev.globalgalashow.com"
echo "Started: $(date)"
echo ""

# Initialize report
cat > "$REPORT_FILE" << EOF
# Security Audit Report
**Generated:** $(date)
**Target:** dev.globalgalashow.com
**Test Suite Version:** 1.0

---

## Executive Summary

EOF

TOTAL_PASS=0
TOTAL_FAIL=0
TOTAL_WARN=0
TOTAL_CRITICAL=0

# Test results array
declare -A TEST_RESULTS

# Function to run a test suite
run_test_suite() {
    local test_name="$1"
    local test_script="$2"
    local test_desc="$3"

    echo -e "\n${BLUE}[Running]${NC} $test_name"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    if [ ! -f "$test_script" ]; then
        echo -e "${RED}[Error]${NC} Test script not found: $test_script"
        return 1
    fi

    chmod +x "$test_script"

    # Run test and capture output
    local output
    local exit_code
    output=$("$test_script" 2>&1)
    exit_code=$?

    # Extract statistics
    local pass=$(echo "$output" | grep -oP 'Passed: \K\d+' | head -1)
    local fail=$(echo "$output" | grep -oP 'Failed: \K\d+' | head -1)
    local warn=$(echo "$output" | grep -oP 'Warnings: \K\d+' | head -1)
    local critical=$(echo "$output" | grep -oP 'Critical: \K\d+' | head -1)
    local defended=$(echo "$output" | grep -oP 'Defended: \K\d+' | head -1)
    local vulnerable=$(echo "$output" | grep -oP 'Vulnerable: \K\d+' | head -1)

    # Handle different output formats
    pass=${pass:-${defended:-0}}
    fail=${fail:-${vulnerable:-0}}
    warn=${warn:-0}
    critical=${critical:-0}

    # Update totals
    TOTAL_PASS=$((TOTAL_PASS + pass))
    TOTAL_FAIL=$((TOTAL_FAIL + fail))
    TOTAL_WARN=$((TOTAL_WARN + warn))
    TOTAL_CRITICAL=$((TOTAL_CRITICAL + critical))

    # Store results
    TEST_RESULTS["$test_name"]="$pass,$fail,$warn,$critical,$exit_code"

    # Display results
    if [ $exit_code -eq 0 ]; then
        echo -e "${GREEN}[Success]${NC} $test_name completed"
    elif [ $exit_code -eq 1 ]; then
        echo -e "${YELLOW}[Warning]${NC} $test_name found issues"
    else
        echo -e "${RED}[Critical]${NC} $test_name found critical vulnerabilities"
    fi

    echo "  Pass: $pass | Fail: $fail | Warn: $warn | Critical: $critical"

    # Append to report
    cat >> "$REPORT_FILE" << EOF

### $test_name

$test_desc

**Results:**
- ✅ Passed: $pass
- ❌ Failed: $fail
- ⚠️  Warnings: $warn
- 🔴 Critical: $critical

**Exit Code:** $exit_code $([ $exit_code -eq 0 ] && echo "(✓ Success)" || echo "(✗ Issues Found)")

<details>
<summary>Detailed Output</summary>

\`\`\`
$output
\`\`\`

</details>

---

EOF

    # Log output
    echo "[$test_name] Exit: $exit_code" >> "$LOG_FILE"
    echo "$output" >> "$LOG_FILE"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" >> "$LOG_FILE"
}

# ============================================================================
# RUN ALL TEST SUITES
# ============================================================================

run_test_suite \
    "Basic Security Audit" \
    "$SCRIPT_DIR/security-audit.sh" \
    "Tests fundamental security controls including authentication, authorization, headers, and file protection."

run_test_suite \
    "Advanced Security Audit" \
    "$SCRIPT_DIR/security-audit-advanced.sh" \
    "Deep-dive testing of authentication mechanisms, data security, injection attacks, session management, GDPR compliance, and infrastructure security."

run_test_suite \
    "Booking System Security" \
    "$SCRIPT_DIR/security-audit-booking.sh" \
    "Specialized tests for seat reservation system including race conditions, payment integrity, hold expiration, and refund security."

run_test_suite \
    "Penetration Testing" \
    "$SCRIPT_DIR/security-pentest.sh" \
    "Real-world attack scenarios including account takeover, data exfiltration, payment manipulation, DoS, code injection, and authentication bypass."

# ============================================================================
# GENERATE FINAL REPORT
# ============================================================================

echo -e "\n${BOLD}======================================"
echo "Test Suite Complete"
echo "======================================${NC}"
echo ""
echo -e "${GREEN}Total Passed:${NC}    $TOTAL_PASS"
echo -e "${YELLOW}Total Warnings:${NC}  $TOTAL_WARN"
echo -e "${RED}Total Failed:${NC}    $TOTAL_FAIL"
echo -e "${RED}Total Critical:${NC}  $TOTAL_CRITICAL"
echo ""

# Calculate security score
TOTAL_TESTS=$((TOTAL_PASS + TOTAL_FAIL + TOTAL_WARN + TOTAL_CRITICAL))
if [ $TOTAL_TESTS -gt 0 ]; then
    SCORE=$((TOTAL_PASS * 100 / TOTAL_TESTS))
else
    SCORE=0
fi

# Determine grade
if [ $TOTAL_CRITICAL -gt 0 ]; then
    GRADE="F"
    GRADE_COLOR="$RED"
elif [ $SCORE -ge 90 ]; then
    GRADE="A"
    GRADE_COLOR="$GREEN"
elif [ $SCORE -ge 80 ]; then
    GRADE="B"
    GRADE_COLOR="$GREEN"
elif [ $SCORE -ge 70 ]; then
    GRADE="C"
    GRADE_COLOR="$YELLOW"
elif [ $SCORE -ge 60 ]; then
    GRADE="D"
    GRADE_COLOR="$YELLOW"
else
    GRADE="F"
    GRADE_COLOR="$RED"
fi

echo -e "${BOLD}Security Score:${NC} ${GRADE_COLOR}$SCORE/100 (Grade: $GRADE)${NC}"
echo ""

# Add summary to report
sed -i '' '/## Executive Summary/a\
\
**Security Score:** '$SCORE'/100 (Grade: '$GRADE')\
\
**Overall Status:** '$([ $TOTAL_CRITICAL -gt 0 ] && echo "🔴 Critical Issues Found" || ([ $TOTAL_FAIL -gt 0 ] && echo "⚠️  Issues Require Attention" || echo "✅ Secure"))'  \
\
**Test Statistics:**\
- Total Tests Run: '$TOTAL_TESTS'\
- Tests Passed: '$TOTAL_PASS'\
- Tests Failed: '$TOTAL_FAIL'\
- Warnings: '$TOTAL_WARN'\
- Critical Issues: '$TOTAL_CRITICAL'\
\
---
' "$REPORT_FILE" 2>/dev/null || {
    # Fallback for Linux sed
    sed -i '/## Executive Summary/a\\n**Security Score:** '$SCORE'/100 (Grade: '$GRADE')\n\n**Overall Status:** '$([ $TOTAL_CRITICAL -gt 0 ] && echo "🔴 Critical Issues Found" || ([ $TOTAL_FAIL -gt 0 ] && echo "⚠️  Issues Require Attention" || echo "✅ Secure"))'  \n\n**Test Statistics:**\n- Total Tests Run: '$TOTAL_TESTS'\n- Tests Passed: '$TOTAL_PASS'\n- Tests Failed: '$TOTAL_FAIL'\n- Warnings: '$TOTAL_WARN'\n- Critical Issues: '$TOTAL_CRITICAL'\n\n---' "$REPORT_FILE"
}

# Add recommendations
cat >> "$REPORT_FILE" << 'EOF'

## Recommendations

### Immediate Actions (Critical)
EOF

if [ $TOTAL_CRITICAL -gt 0 ]; then
    echo "- 🔴 **Address $TOTAL_CRITICAL critical vulnerabilities immediately**" >> "$REPORT_FILE"
    echo "- Review penetration test results for exploitable vulnerabilities" >> "$REPORT_FILE"
    echo "- Implement emergency patches before production deployment" >> "$REPORT_FILE"
else
    echo "- ✅ No critical vulnerabilities detected" >> "$REPORT_FILE"
fi

cat >> "$REPORT_FILE" << EOF

### Short-term (1-2 weeks)
- Address $TOTAL_FAIL failed security tests
- Review and resolve $TOTAL_WARN warnings
- Implement additional input validation
- Strengthen rate limiting on sensitive endpoints
- Enable HSTS header for production HTTPS

### Long-term (1-3 months)
- Implement Web Application Firewall (WAF)
- Set up continuous security monitoring
- Conduct regular penetration testing
- Implement security logging and alerting
- Review and update security policies

### Security Best Practices
- Keep all dependencies up to date
- Regular security audits (monthly recommended)
- Implement bug bounty program
- Security training for development team
- Automated security testing in CI/CD pipeline

---

## Detailed Test Results

See sections above for individual test suite results.

---

**Report Generated:** $(date)
**Next Audit Recommended:** $(date -d "+1 month" +%Y-%m-%d 2>/dev/null || date -v+1m +%Y-%m-%d 2>/dev/null || echo "1 month from now")
EOF

echo -e "${BOLD}Report saved to:${NC} $REPORT_FILE"
echo -e "${BOLD}Logs saved to:${NC} $LOG_FILE"
echo ""

# Display actionable summary
if [ $TOTAL_CRITICAL -gt 0 ]; then
    echo -e "${RED}${BOLD}⚠️  CRITICAL: Immediate action required!${NC}"
    echo -e "${RED}$TOTAL_CRITICAL critical vulnerabilities must be fixed before production.${NC}"
    exit 2
elif [ $TOTAL_FAIL -gt 5 ]; then
    echo -e "${YELLOW}${BOLD}⚠️  WARNING: Multiple security issues detected${NC}"
    echo -e "${YELLOW}$TOTAL_FAIL issues should be addressed soon.${NC}"
    exit 1
elif [ $TOTAL_FAIL -gt 0 ] || [ $TOTAL_WARN -gt 5 ]; then
    echo -e "${YELLOW}${BOLD}✓ Generally secure with minor issues${NC}"
    echo -e "${YELLOW}Review warnings and failed tests for improvements.${NC}"
    exit 0
else
    echo -e "${GREEN}${BOLD}✓ Excellent security posture!${NC}"
    echo -e "${GREEN}System passed all security tests.${NC}"
    exit 0
fi
