#!/bin/bash

# Container Image Scanner - Security Testing Script (Fixed)
# This script performs comprehensive security testing with reduced false positives

set -euo pipefail

# Detect if colors should be used
USE_COLOR=true
if [[ "${NO_COLOR:-}" = "1" ]] || [[ "${TERM:-}" = "dumb" ]] || ! [[ -t 1 ]]; then
    USE_COLOR=false
fi

# Colors for output
if $USE_COLOR; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    BLUE='\033[0;34m'
    NC='\033[0m' # No Color
else
    RED=''
    GREEN=''
    YELLOW=''
    BLUE=''
    NC=''
fi

# Test results
PASSED=0
FAILED=0
WARNINGS=0

echo -e "${BLUE}🔒 Container Image Scanner - Security Testing${NC}"
echo "=================================================="

# Function to print test results
print_result() {
    local test_name="$1"
    local result="$2"
    local message="$3"
    
    if [ "$result" = "PASS" ]; then
        echo -e "✅ ${GREEN}PASS${NC}: $test_name - $message"
        ((PASSED++))
    elif [ "$result" = "FAIL" ]; then
        echo -e "❌ ${RED}FAIL${NC}: $test_name - $message"
        ((FAILED++))
    else
        echo -e "⚠️  ${YELLOW}WARN${NC}: $test_name - $message"
        ((WARNINGS++))
    fi
}

# Test 1: Check for actual hardcoded secrets (more precise)
echo -e "\n${BLUE}1. Checking for hardcoded secrets...${NC}"
# Look for actual secret patterns, not just the words
if grep -r -E "(password|secret|key|token)\s*[:=]\s*['\"][^'\"]{8,}" src/ --exclude-dir=node_modules --exclude="*.md" --exclude="*.backup*" | grep -v "CHANGE_ME" | grep -v "process.env" | grep -v "{ \[key: string\]" | grep -v "keyof" > /dev/null 2>&1; then
    print_result "Hardcoded Secrets" "FAIL" "Found potential hardcoded secrets in source code"
    grep -r -E "(password|secret|key|token)\s*[:=]\s*['\"][^'\"]{8,}" src/ --exclude-dir=node_modules --exclude="*.md" --exclude="*.backup*" | grep -v "CHANGE_ME" | grep -v "process.env" | grep -v "{ \[key: string\]" | grep -v "keyof" || true
else
    print_result "Hardcoded Secrets" "PASS" "No hardcoded secrets found"
fi

# Test 2: Check .gitignore for sensitive files
echo -e "\n${BLUE}2. Checking .gitignore configuration...${NC}"
if grep -q "\.env" .gitignore && grep -q "aws-credentials" .gitignore && grep -q "\.aws/" .gitignore; then
    print_result "Gitignore Configuration" "PASS" "Sensitive files properly excluded"
else
    print_result "Gitignore Configuration" "FAIL" "Missing sensitive file exclusions in .gitignore"
fi

# Test 3: Check npm audit
echo -e "\n${BLUE}3. Running npm security audit...${NC}"
if npm audit --audit-level moderate > /dev/null 2>&1; then
    print_result "NPM Security Audit" "PASS" "No moderate or high severity vulnerabilities found"
else
    print_result "NPM Security Audit" "FAIL" "Security vulnerabilities found in dependencies"
fi

# Test 4: Check for proper error handling
echo -e "\n${BLUE}4. Checking error handling...${NC}"
if grep -r "console.error.*error\." src/ > /dev/null 2>&1; then
    print_result "Error Handling" "PASS" "Proper error handling found"
else
    print_result "Error Handling" "WARN" "Review error handling implementation"
fi

# Test 5: Check TypeScript configuration
echo -e "\n${BLUE}5. Checking TypeScript security settings...${NC}"
if [ -f "tsconfig.json" ]; then
    if grep -q '"strict": true' tsconfig.json; then
        print_result "TypeScript Configuration" "PASS" "Strict mode enabled"
    else
        print_result "TypeScript Configuration" "WARN" "TypeScript strict mode not enabled"
    fi
else
    print_result "TypeScript Configuration" "FAIL" "No TypeScript configuration found"
fi

# Test 6: Check for console.log in production code (excluding backup files)
echo -e "\n${BLUE}6. Checking for debug statements...${NC}"
if grep -r "console.log" src/ --exclude="*.test.ts" --exclude="*.spec.ts" --exclude="*.backup*" > /dev/null 2>&1; then
    print_result "Debug Statements" "WARN" "Found console.log statements in production code"
else
    print_result "Debug Statements" "PASS" "No debug statements found in production code"
fi

# Test 7: Check AWS credential usage (more precise)
echo -e "\n${BLUE}7. Checking AWS credential handling...${NC}"
if grep -r -E "AWS_ACCESS_KEY.*=.*['\"][A-Z0-9]{20}" src/ > /dev/null 2>&1; then
    print_result "AWS Credentials" "FAIL" "Hardcoded AWS credentials found"
else
    print_result "AWS Credentials" "PASS" "No hardcoded AWS credentials found"
fi

# Test 8: Check for rate limiting
echo -e "\n${BLUE}8. Checking rate limiting implementation...${NC}"
if grep -r "rateLimit\|rate.*limit" src/ > /dev/null 2>&1; then
    print_result "Rate Limiting" "PASS" "Rate limiting implementation found"
else
    print_result "Rate Limiting" "WARN" "No rate limiting implementation found"
fi

# Test 9: Check for security headers
echo -e "\n${BLUE}9. Checking security headers...${NC}"
if grep -r "helmet" src/ > /dev/null 2>&1; then
    print_result "Security Headers" "PASS" "Security headers implementation found"
else
    print_result "Security Headers" "WARN" "No security headers implementation found"
fi

# Test 10: Check for proper CORS configuration
echo -e "\n${BLUE}10. Checking CORS configuration...${NC}"
if grep -r "cors" src/ > /dev/null 2>&1; then
    if grep -r "origin.*localhost\|origin.*127.0.0.1" src/ > /dev/null 2>&1; then
        print_result "CORS Configuration" "PASS" "Restrictive CORS configuration found"
    else
        print_result "CORS Configuration" "WARN" "CORS found but may be too permissive"
    fi
else
    print_result "CORS Configuration" "WARN" "No CORS configuration found"
fi

# Test 11: Check for input validation
echo -e "\n${BLUE}11. Checking input validation...${NC}"
if grep -r "validate\|validation" src/ > /dev/null 2>&1; then
    print_result "Input Validation" "PASS" "Input validation implementation found"
else
    print_result "Input Validation" "WARN" "No explicit input validation found"
fi

# Test 12: Check for dependency pinning
echo -e "\n${BLUE}12. Checking dependency pinning...${NC}"
if [ -f "package-lock.json" ]; then
    print_result "Dependency Pinning" "PASS" "package-lock.json found - dependencies are pinned"
else
    print_result "Dependency Pinning" "WARN" "No package-lock.json found - dependencies not pinned"
fi

# Test 13: Check for test coverage
echo -e "\n${BLUE}13. Checking test coverage...${NC}"
if [ -d "tests" ] || [ -d "test" ] || grep -q "jest\|mocha\|jasmine" package.json; then
    print_result "Test Coverage" "PASS" "Testing framework found"
else
    print_result "Test Coverage" "WARN" "No testing framework found"
fi

# Test 14: Check for security documentation
echo -e "\n${BLUE}14. Checking security documentation...${NC}"
if [ -f "SECURITY.md" ] || [ -f "SECURITY-REVIEW.md" ] || grep -i security README.md > /dev/null 2>&1; then
    print_result "Security Documentation" "PASS" "Security documentation found"
else
    print_result "Security Documentation" "WARN" "No security documentation found"
fi

# Test 15: Check for environment-specific configurations
echo -e "\n${BLUE}15. Checking environment configurations...${NC}"
if grep -r "NODE_ENV" src/ > /dev/null 2>&1; then
    print_result "Environment Configuration" "PASS" "Environment-specific configuration found"
else
    print_result "Environment Configuration" "WARN" "No environment-specific configuration found"
fi

# Summary
echo -e "\n${BLUE}Security Test Summary${NC}"
echo "===================="
echo -e "✅ ${GREEN}Passed: $PASSED${NC}"
echo -e "⚠️  ${YELLOW}Warnings: $WARNINGS${NC}"
echo -e "❌ ${RED}Failed: $FAILED${NC}"

# Overall result
if [ $FAILED -eq 0 ]; then
    if [ $WARNINGS -eq 0 ]; then
        echo -e "\n🎉 ${GREEN}All security tests passed!${NC}"
        exit 0
    else
        echo -e "\n⚠️  ${YELLOW}Security tests passed with warnings. Review warnings above.${NC}"
        exit 0
    fi
else
    echo -e "\n💥 ${RED}Security tests failed! Address the failures above before deployment.${NC}"
    exit 1
fi
