#!/bin/bash
# Security Audit Script
# Runs comprehensive security checks on the codebase

set -e

echo "🔒 Starting Security Audit..."

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

# Check if required tools are installed
check_tool() {
    if ! command -v $1 &> /dev/null; then
        echo -e "${YELLOW}Warning: $1 is not installed. Skipping $1 checks.${NC}"
        return 1
    fi
    return 0
}

# Run ESLint security checks
echo "📋 Running ESLint security checks..."
if check_tool eslint; then
    pnpm lint --filter "./packages/**" --filter "./services/**" 2>&1 | tee security-audit-eslint.log || true
    echo -e "${GREEN}✓ ESLint security checks completed${NC}"
else
    echo -e "${YELLOW}⚠ ESLint not available${NC}"
fi

# Check for hardcoded secrets
echo "🔍 Checking for hardcoded secrets..."
if check_tool grep; then
    # Common secret patterns
    SECRET_PATTERNS=(
        "password.*=.*['\"][^'\"]+['\"]"
        "secret.*=.*['\"][^'\"]+['\"]"
        "api[_-]?key.*=.*['\"][^'\"]+['\"]"
        "token.*=.*['\"][^'\"]+['\"]"
        "aws[_-]?secret[_-]?access[_-]?key"
        "private[_-]?key.*=.*['\"][^'\"]+['\"]"
    )
    
    SECRETS_FOUND=0
    for pattern in "${SECRET_PATTERNS[@]}"; do
        if grep -r -i -E "$pattern" --include="*.ts" --include="*.js" --include="*.tsx" --include="*.jsx" \
            --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=build --exclude-dir=.next \
            --exclude="*.test.ts" --exclude="*.spec.ts" . 2>/dev/null | grep -v "test-secret\|example\|placeholder\|TODO" > /dev/null; then
            echo -e "${RED}⚠ Potential hardcoded secret found with pattern: $pattern${NC}"
            SECRETS_FOUND=1
        fi
    done
    
    if [ $SECRETS_FOUND -eq 0 ]; then
        echo -e "${GREEN}✓ No hardcoded secrets found${NC}"
    else
        echo -e "${YELLOW}⚠ Review potential secrets manually${NC}"
    fi
fi

# Check for vulnerable dependencies
echo "📦 Checking for vulnerable dependencies..."
if check_tool pnpm; then
    pnpm audit --audit-level moderate 2>&1 | tee security-audit-dependencies.log || true
    echo -e "${GREEN}✓ Dependency audit completed${NC}"
fi

# Check for outdated dependencies
echo "🔄 Checking for outdated dependencies..."
if check_tool pnpm; then
    pnpm outdated 2>&1 | tee security-audit-outdated.log || true
    echo -e "${GREEN}✓ Outdated dependencies check completed${NC}"
fi

# Run Trivy scan if available
echo "🔍 Running Trivy vulnerability scan..."
if check_tool trivy; then
    trivy fs --severity HIGH,CRITICAL . 2>&1 | tee security-audit-trivy.log || true
    echo -e "${GREEN}✓ Trivy scan completed${NC}"
fi

# Check for insecure TLS/SSL configurations
echo "🔐 Checking for insecure TLS/SSL configurations..."
if check_tool grep; then
    INSECURE_TLS=0
    if grep -r -i "tlsv1\|sslv3\|TLSv1.0\|TLSv1.1" --include="*.ts" --include="*.js" \
        --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=build . 2>/dev/null; then
        echo -e "${RED}⚠ Insecure TLS/SSL versions found${NC}"
        INSECURE_TLS=1
    fi
    
    if [ $INSECURE_TLS -eq 0 ]; then
        echo -e "${GREEN}✓ No insecure TLS/SSL configurations found${NC}"
    fi
fi

# Check for SQL injection vulnerabilities
echo "💉 Checking for SQL injection vulnerabilities..."
if check_tool grep; then
    SQL_INJECTION=0
    # Check for string concatenation in SQL queries
    if grep -r -E "query.*\+.*['\"]|query.*\$\{|query.*\`.*\$\{" \
        --include="*.ts" --include="*.js" \
        --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=build \
        --exclude="*.test.ts" --exclude="*.spec.ts" . 2>/dev/null; then
        echo -e "${YELLOW}⚠ Potential SQL injection vulnerabilities found. Review queries manually.${NC}"
        SQL_INJECTION=1
    fi
    
    if [ $SQL_INJECTION -eq 0 ]; then
        echo -e "${GREEN}✓ No obvious SQL injection patterns found${NC}"
    fi
fi

# Check for XSS vulnerabilities
echo "🌐 Checking for XSS vulnerabilities..."
if check_tool grep; then
    XSS=0
    # Check for innerHTML usage without sanitization
    if grep -r "innerHTML\|dangerouslySetInnerHTML" \
        --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" \
        --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=build \
        --exclude="*.test.ts" --exclude="*.spec.ts" . 2>/dev/null; then
        echo -e "${YELLOW}⚠ Potential XSS vulnerabilities found. Review innerHTML usage.${NC}"
        XSS=1
    fi
    
    if [ $XSS -eq 0 ]; then
        echo -e "${GREEN}✓ No obvious XSS patterns found${NC}"
    fi
fi

# Check for insecure random number generation
echo "🎲 Checking for insecure random number generation..."
if check_tool grep; then
    INSECURE_RANDOM=0
    if grep -r "Math\.random\|random\(\)" \
        --include="*.ts" --include="*.js" \
        --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=build \
        --exclude="*.test.ts" --exclude="*.spec.ts" . 2>/dev/null | grep -v "crypto\.randomBytes\|crypto\.getRandomValues"; then
        echo -e "${YELLOW}⚠ Potential insecure random number generation found. Use crypto.randomBytes or crypto.getRandomValues.${NC}"
        INSECURE_RANDOM=1
    fi
    
    if [ $INSECURE_RANDOM -eq 0 ]; then
        echo -e "${GREEN}✓ No insecure random number generation found${NC}"
    fi
fi

# Generate security audit report
echo "📊 Generating security audit report..."
REPORT_FILE="security-audit-report-$(date +%Y%m%d-%H%M%S).md"
cat > "$REPORT_FILE" << EOF
# Security Audit Report

**Date**: $(date)
**Auditor**: Automated Security Audit Script
**Scope**: The Order Monorepo

## Summary

This report contains the results of automated security checks.

## Checks Performed

1. ESLint Security Checks
2. Hardcoded Secrets Detection
3. Vulnerable Dependencies
4. Outdated Dependencies
5. Trivy Vulnerability Scan
6. TLS/SSL Configuration
7. SQL Injection Vulnerabilities
8. XSS Vulnerabilities
9. Insecure Random Number Generation

## Findings

See individual log files for detailed findings:
- \`security-audit-eslint.log\`
- \`security-audit-dependencies.log\`
- \`security-audit-outdated.log\`
- \`security-audit-trivy.log\`

## Recommendations

1. Review all findings and address high-priority issues
2. Update vulnerable dependencies
3. Implement security best practices
4. Conduct manual security review
5. Schedule penetration testing

## Next Steps

1. Review security audit checklist: \`docs/governance/SECURITY_AUDIT_CHECKLIST.md\`
2. Review threat model: \`docs/governance/THREAT_MODEL.md\`
3. Address findings according to priority
4. Schedule follow-up audit

EOF

echo -e "${GREEN}✓ Security audit report generated: $REPORT_FILE${NC}"
echo ""
echo "🔒 Security Audit Complete!"
echo "📋 Review the audit report and log files for detailed findings."
echo "📝 Next steps:"
echo "   1. Review security-audit-report-*.md"
echo "   2. Address high-priority findings"
echo "   3. Schedule manual security review"
echo "   4. Conduct penetration testing"

