#!/bin/bash

# Local Security Testing Script
# Run SAST and basic security checks locally before pushing

set -e

echo "🔒 Starting Local Security Tests..."
echo ""

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

# Function to print colored output
print_status() {
    echo -e "${2}${1}${NC}"
}

# 1. NPM Audit
print_status "📦 Running NPM Audit..." "$YELLOW"
echo "Backend:"
cd backend
npm audit --audit-level=moderate || true
cd ..

echo ""
echo "Frontend:"
cd frontend
npm audit --audit-level=moderate || true
cd ..
echo ""

# 2. ESLint Security Check
print_status "🔍 Running ESLint Security Scan..." "$YELLOW"
echo "Installing eslint-plugin-security if needed..."
cd backend
npm install --save-dev eslint eslint-plugin-security 2>/dev/null || true
npx eslint . --ext .js || print_status "⚠️  Backend ESLint issues found" "$YELLOW"
cd ..

cd frontend
npm install --save-dev eslint eslint-plugin-security eslint-plugin-react eslint-plugin-react-hooks 2>/dev/null || true
npx eslint . --ext .js,.jsx || print_status "⚠️  Frontend ESLint issues found" "$YELLOW"
cd ..
echo ""

# 3. Sensitive Data Check
print_status "🔐 Checking for sensitive data..." "$YELLOW"
if grep -r -i "password.*=" --include="*.js" --include="*.jsx" --exclude-dir="node_modules" . | grep -v "password.*process.env" | grep -v "password.*req.body" | grep -v "password:" | grep -v "// password"; then
    print_status "⚠️  Potential hardcoded passwords found" "$RED"
else
    print_status "✅ No hardcoded passwords detected" "$GREEN"
fi

if grep -r "api[_-]?key.*=.*['\"][a-zA-Z0-9]" --include="*.js" --include="*.jsx" --exclude-dir="node_modules" . | grep -v "process.env"; then
    print_status "⚠️  Potential hardcoded API keys found" "$RED"
else
    print_status "✅ No hardcoded API keys detected" "$GREEN"
fi
echo ""

# 4. SQL Injection Check
print_status "💉 Checking for SQL injection vulnerabilities..." "$YELLOW"
if grep -r "db.run\|db.all\|db.get" --include="*.js" backend/ | grep -v "?" | grep -v "\[" | grep "\`"; then
    print_status "⚠️  Potential SQL injection vulnerabilities found (template literals)" "$RED"
else
    print_status "✅ No obvious SQL injection issues" "$GREEN"
fi
echo ""

# 5. XSS Check
print_status "🌐 Checking for XSS vulnerabilities..." "$YELLOW"
if grep -r "dangerouslySetInnerHTML\|innerHTML" --include="*.js" --include="*.jsx" frontend/src/ ; then
    print_status "⚠️  Potential XSS vulnerabilities found" "$YELLOW"
else
    print_status "✅ No obvious XSS issues" "$GREEN"
fi
echo ""

# 6. Dependency Check
print_status "📚 Checking dependency versions..." "$YELLOW"
outdated_backend=$(cd backend && npm outdated || true)
outdated_frontend=$(cd frontend && npm outdated || true)

if [ ! -z "$outdated_backend" ] || [ ! -z "$outdated_frontend" ]; then
    print_status "⚠️  Outdated dependencies found. Run 'npm outdated' for details" "$YELLOW"
else
    print_status "✅ All dependencies up to date" "$GREEN"
fi
echo ""

# 7. Docker Security (if Docker is available)
if command -v docker &> /dev/null; then
    print_status "🐳 Checking Docker configuration..." "$YELLOW"
    
    if grep -q "latest" Dockerfile; then
        print_status "⚠️  Using 'latest' tag in Dockerfile is not recommended" "$YELLOW"
    fi
    
    if ! grep -q "USER" Dockerfile; then
        print_status "⚠️  Dockerfile doesn't specify non-root USER" "$YELLOW"
    else
        print_status "✅ Dockerfile uses non-root user" "$GREEN"
    fi
else
    print_status "ℹ️  Docker not available, skipping Docker checks" "$YELLOW"
fi
echo ""

# 8. Environment Variables Check
print_status "🔑 Checking environment configuration..." "$YELLOW"
if [ -f ".env" ]; then
    print_status "⚠️  .env file found - ensure it's in .gitignore!" "$YELLOW"
    if grep -q ".env" .gitignore; then
        print_status "✅ .env is in .gitignore" "$GREEN"
    else
        print_status "❌ .env NOT in .gitignore - SECURITY RISK!" "$RED"
    fi
else
    print_status "✅ No .env file in root directory" "$GREEN"
fi
echo ""

# Summary
print_status "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" "$GREEN"
print_status "✅ Local security checks completed!" "$GREEN"
print_status "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" "$GREEN"
echo ""
print_status "💡 For comprehensive security testing:" "$YELLOW"
echo "   1. Push to GitHub to trigger automated SAST/DAST scans"
echo "   2. Run 'npm run security:full' for detailed reports"
echo "   3. Review GitHub Security tab for vulnerability alerts"
echo ""
