#!/bin/bash

# Frontend Security Scanning Script
# Scans for security vulnerabilities, malware, and suspicious patterns

set -e

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

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
FRONTEND_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"

echo -e "${BLUE}=========================================="
echo "Frontend Security Scan"
echo "==========================================${NC}"
echo ""

# Check if running from correct directory
if [ ! -f "$FRONTEND_DIR/package.json" ]; then
    echo -e "${RED}Error: package.json not found. Run from frontend directory.${NC}"
    exit 1
fi

cd "$FRONTEND_DIR"

# 1. Check for postinstall scripts
echo -e "${BLUE}[1/8] Checking for postinstall scripts...${NC}"
if grep -q '"postinstall"' package.json; then
    echo -e "${RED}⚠️  WARNING: postinstall script found in package.json${NC}"
    grep -A 5 '"postinstall"' package.json
else
    echo -e "${GREEN}✅ No postinstall scripts found${NC}"
fi
echo ""

# 2. Check for suspicious scripts (curl, wget, sh execution)
echo -e "${BLUE}[2/8] Scanning for suspicious script executions...${NC}"
SUSPICIOUS_FOUND=0

# Check TypeScript/JavaScript files (exclude false positives)
if grep -r -E "(curl|wget|exec\(|spawn|child_process|\.sh|bash |sh )" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" . 2>/dev/null | \
   grep -v "node_modules" | \
   grep -v ".next" | \
   grep -v "security-scan.sh" | \
   grep -v "start-services.sh" | \
   grep -v "deploy.sh" | \
   grep -v "short_description" | \
   grep -v "Refresh" | \
   grep -v "showSettings" | \
   grep -v "showBanner" | \
   grep -v "refresh" | \
   grep -v "Service not found"; then
    echo -e "${YELLOW}⚠️  Found potential script execution patterns (review manually)${NC}"
    SUSPICIOUS_FOUND=1
else
    echo -e "${GREEN}✅ No suspicious script executions found${NC}"
fi
echo ""

# 3. Check for dangerous patterns (eval, Function, innerHTML)
echo -e "${BLUE}[3/8] Scanning for dangerous code patterns...${NC}"
DANGEROUS_FOUND=0

# Check for dangerous patterns (exclude safe uses)
if grep -r -E "(eval\(|Function\(|\.innerHTML\s*=|dangerouslySetInnerHTML)" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" . 2>/dev/null | \
   grep -v "node_modules" | \
   grep -v ".next" | \
   grep -v "sanitize" | \
   grep -v "lib/security" | \
   grep -v "JSON.stringify" | \
   grep -v "StructuredData" | \
   grep -v "app/layout.tsx.*scrollRestoration" | \
   grep -v "app/layout.tsx.*DOMContentLoaded"; then
    echo -e "${YELLOW}⚠️  Found dangerous patterns (should use sanitization)${NC}"
    DANGEROUS_FOUND=1
else
    echo -e "${GREEN}✅ No unsanitized dangerous patterns found${NC}"
fi
echo ""

# 4. Check for exposed secrets
echo -e "${BLUE}[4/8] Scanning for exposed secrets...${NC}"
SECRETS_FOUND=0

# Check for API keys, passwords, tokens
if grep -r -E "(api[_-]?key|secret[_-]?key|password|token|private[_-]?key)" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" -i . 2>/dev/null | grep -v "node_modules" | grep -v ".next" | grep -v "NEXT_PUBLIC_" | grep -v "process.env" | grep -v "INTERNAL_API_KEY" | grep -v "lib/config" | grep -v "SECURITY_AUDIT"; then
    echo -e "${YELLOW}⚠️  Potential secrets found (review manually)${NC}"
    SECRETS_FOUND=1
else
    echo -e "${GREEN}✅ No exposed secrets found${NC}"
fi
echo ""

# 5. Run npm audit
echo -e "${BLUE}[5/8] Running npm audit...${NC}"
if npm audit --audit-level=moderate 2>/dev/null; then
    echo -e "${GREEN}✅ No critical vulnerabilities found${NC}"
else
    echo -e "${YELLOW}⚠️  Vulnerabilities found. Run 'npm audit fix' to fix automatically.${NC}"
fi
echo ""

# 6. Check for outdated packages
echo -e "${BLUE}[6/8] Checking for outdated packages...${NC}"
OUTDATED=$(npm outdated 2>/dev/null | wc -l)
if [ "$OUTDATED" -gt 1 ]; then
    echo -e "${YELLOW}⚠️  Found $((OUTDATED - 1)) outdated packages${NC}"
    npm outdated 2>/dev/null | head -10
else
    echo -e "${GREEN}✅ All packages are up to date${NC}"
fi
echo ""

# 7. Check .env files are not committed
echo -e "${BLUE}[7/8] Checking .env file security...${NC}"
if [ -f ".env" ] && git ls-files --error-unmatch .env >/dev/null 2>&1; then
    echo -e "${RED}⚠️  WARNING: .env file is tracked in git!${NC}"
else
    echo -e "${GREEN}✅ .env files are not tracked in git${NC}"
fi
echo ""

# 8. Check for malware patterns (basic scan)
echo -e "${BLUE}[8/8] Scanning for malware patterns...${NC}"
MALWARE_PATTERNS=(
    "base64_decode"
    "eval(base64"
    "gzinflate"
    "str_rot13"
    "preg_replace.*\/e"
    "assert.*eval"
    "system\("
    "shell_exec\("
    "passthru\("
    "proc_open\("
)

MALWARE_FOUND=0
for pattern in "${MALWARE_PATTERNS[@]}"; do
    # Exclude security config file (it contains patterns we check FOR, not actual malware)
    if grep -r -E "$pattern" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" . 2>/dev/null | \
       grep -v "node_modules" | \
       grep -v ".next" | \
       grep -v "lib/security/config.ts" | \
       grep -v "SUSPICIOUS_PATTERNS"; then
        echo -e "${RED}⚠️  WARNING: Potential malware pattern found: $pattern${NC}"
        MALWARE_FOUND=1
    fi
done

if [ $MALWARE_FOUND -eq 0 ]; then
    echo -e "${GREEN}✅ No malware patterns detected${NC}"
fi
echo ""

# Summary
echo -e "${BLUE}=========================================="
echo "Security Scan Summary"
echo "==========================================${NC}"

ISSUES=0
if [ $SUSPICIOUS_FOUND -eq 1 ]; then
    echo -e "${YELLOW}⚠️  Suspicious patterns found${NC}"
    ISSUES=$((ISSUES + 1))
fi
if [ $DANGEROUS_FOUND -eq 1 ]; then
    echo -e "${YELLOW}⚠️  Dangerous code patterns found${NC}"
    ISSUES=$((ISSUES + 1))
fi
if [ $SECRETS_FOUND -eq 1 ]; then
    echo -e "${YELLOW}⚠️  Potential secrets found${NC}"
    ISSUES=$((ISSUES + 1))
fi
if [ $MALWARE_FOUND -eq 1 ]; then
    echo -e "${RED}⚠️  Malware patterns detected${NC}"
    ISSUES=$((ISSUES + 1))
fi

if [ $ISSUES -eq 0 ]; then
    echo -e "${GREEN}✅ Security scan completed. No critical issues found.${NC}"
    exit 0
else
    echo -e "${YELLOW}⚠️  Security scan completed with $ISSUES issue(s) found.${NC}"
    echo -e "${YELLOW}Please review the warnings above.${NC}"
    exit 1
fi

