#!/bin/bash

# WordPress Plugin Security Checker
set -e

GITHUB_ACTIONS=false
[[ "$1" == "--github-actions" ]] && GITHUB_ACTIONS=true

if [[ "$1" == "--help" ]]; then
    echo "Usage: $0 [--github-actions]"
    exit 0
fi

# Temp files for counting
error_file=$(mktemp)
warning_file=$(mktemp)
echo "0" > "$error_file"
echo "0" > "$warning_file"

# Cleanup temp files on exit
trap 'rm -f "$error_file" "$warning_file"' EXIT

# Output function
out() {
    local level="$1" file="$2" line="$3" message="$4" title="$5"

    if [[ "$GITHUB_ACTIONS" == "true" ]]; then
        echo "::${level} file=${file},line=${line},title=${title}::${message}"
    else
        local icon="⚠️" && [[ "$level" == "error" ]] && icon="❌"
        echo "${icon} ${file}:${line} - ${title}"
        echo "   ${message}"
    fi
    
    # Increment counters
    if [[ "$level" == "error" ]]; then
        echo $(($(cat "$error_file") + 1)) > "$error_file"
    else
        echo $(($(cat "$warning_file") + 1)) > "$warning_file"
    fi
}

# Security checks
check_pattern() {
    local pattern="$1" level="$2" title="$3" message="$4"

    grep -rn "$pattern" --include="*.php" --exclude-dir="node_modules" --exclude-dir="vendor" --exclude-dir="build" . 2>/dev/null | while IFS=: read -r file line content; do
        [[ -n "$file" ]] && out "$level" "$file" "$line" "$message" "$title"
    done
}

echo "🛡️ WordPress Plugin Security Checker"

# 1. ABSPATH Protection
find . -name "*.php" -not -path "./node_modules/*" -not -path "./vendor/*" -not -path "./build/*" | while read -r file; do
    if ! grep -q "defined.*ABSPATH" "$file" 2>/dev/null; then
        out "warning" "$file" "1" "Add: if ( ! defined( 'ABSPATH' ) ) { exit; }" "Missing ABSPATH Protection"
    fi
done

# 2. SQL Injection
check_pattern "\\\$wpdb->query.*\\\$_" "error" "SQL Injection Risk" "Direct user input in query. Use prepared statements."

# 3. XSS
check_pattern "echo.*\\\$_\\(GET\\|POST\\|REQUEST\\)" "error" "XSS Risk" "Direct output of user input. Use esc_html(), esc_attr()."

# 4. Unescaped Output
check_pattern "echo.*\\(get_option\\|get_user_meta\\|get_post_meta\\)" "warning" "Unescaped Output" "Consider using esc_html() or esc_attr()."

# 5. Missing Nonce
grep -rl "\\\$_POST" --include="*.php" --exclude-dir="node_modules" --exclude-dir="vendor" --exclude-dir="build" . 2>/dev/null | while read -r file; do
    if ! grep -q "wp_verify_nonce\\|check_admin_referer\\|check_ajax_referer" "$file"; then
        line_num=$(grep -n "\\\$_POST" "$file" | head -1 | cut -d: -f1)
        out "warning" "$file" "$line_num" "Add wp_verify_nonce() for CSRF protection." "Missing Nonce Verification"
    fi
done

# 6. File Uploads
check_pattern "\\\$_FILES\\|move_uploaded_file\\|wp_handle_upload" "warning" "File Upload Security" "Validate file types and destinations."

# Get final counts and exit appropriately
error_count=$(cat "$error_file")
warning_count=$(cat "$warning_file")

if [[ "$GITHUB_ACTIONS" == "false" ]]; then
    if [[ $error_count -eq 0 && $warning_count -eq 0 ]]; then
        echo "✅ No security issues found!"
    else
        echo "❌ Errors: $error_count, ⚠️  Warnings: $warning_count"
    fi
fi

# Exit with error code if critical issues found
[[ $error_count -gt 0 ]] && exit 1 || exit 0
