#!/bin/bash
# github-action/entrypoint.sh - Script d'entrée pour l'action GitHub

set -e

echo "🚀 Web Sentinel Security Scan Starting..."
echo "📁 Source path: $WS_SOURCE_PATH"
echo "🔧 Languages: $WS_LANGUAGES"
echo "⚡ Severity: $WS_SEVERITY_MIN"

# Vérifier la clé API
if [ -z "$WS_API_KEY" ]; then
    echo "❌ Error: WS_API_KEY is required"
    exit 1
fi

# Créer le répertoire de travail
cd /workspace
cp -r /github/workspace/* . 2>/dev/null || true

# Variables de configuration
API_URL="https://api.web-sentinel.com"
REPORT_FILE="web-sentinel-report.json"
SARIF_FILE="web-sentinel.sarif"

# Fonction pour scanner un fichier
scan_file() {
    local file="$1"
    local language="$2"
    
    echo "🔍 Scanning: $file"
    
    # Appel à l'API Web Sentinel
    curl -s -X POST "$API_URL/api/v1/scan-source" \
        -H "Content-Type: application/json" \
        -H "User-Agent: Web-Sentinel-GitHub-Action/1.0" \
        -d "{
            \"source_content\": \"$(cat "$file" | jq -Rs .)\",
            \"file_path\": \"$file\",
            \"language\": \"$language\",
            \"api_key\": \"$WS_API_KEY\",
            \"options\": {
                \"severity_min\": \"$WS_SEVERITY_MIN\",
                \"detailed_report\": true,
                \"format\": \"sarif\"
            }
        }" || echo "Failed to scan $file"
}

# Détecter la langue d'un fichier
detect_language() {
    local file="$1"
    case "${file##*.}" in
        php) echo "php" ;;
        js|ts) echo "javascript" ;;
        py) echo "python" ;;
        java) echo "java" ;;
        cs) echo "csharp" ;;
        go) echo "go" ;;
        *) echo "auto" ;;
    esac
}

# Scanner tous les fichiers si languages=auto
if [ "$WS_LANGUAGES" = "auto" ]; then
    WS_LANGUAGES="php,javascript,python,java,csharp,go"
fi

# Créer la liste des extensions à scanner
extensions=""
IFS=',' read -ra LANGS <<< "$WS_LANGUAGES"
for lang in "${LANGS[@]}"; do
    case "$lang" in
        php) extensions="$extensions -name '*.php'" ;;
        javascript) extensions="$extensions -name '*.js' -o -name '*.ts'" ;;
        python) extensions="$extensions -name '*.py'" ;;
        java) extensions="$extensions -name '*.java'" ;;
        csharp) extensions="$extensions -name '*.cs'" ;;
        go) extensions="$extensions -name '*.go'" ;;
    esac
done

# Trouver et scanner les fichiers
total_findings=0
scanned_files=0

echo "🔍 Searching for source files..."

# Utiliser find pour localiser les fichiers
if [ -n "$extensions" ]; then
    eval "find $WS_SOURCE_PATH -type f \( $extensions \) -not -path '*/node_modules/*' -not -path '*/vendor/*' -not -path '*/dist/*' -not -path '*/build/*'" | while read -r file; do
        
        if [ -f "$file" ]; then
            language=$(detect_language "$file")
            scan_result=$(scan_file "$file" "$language")
            
            # Traiter le résultat (exemple simplifié)
            findings_count=$(echo "$scan_result" | jq -r '.findings | length' 2>/dev/null || echo "0")
            total_findings=$((total_findings + findings_count))
            scanned_files=$((scanned_files + 1))
            
            if [ "$findings_count" -gt 0 ]; then
                echo "⚠️  $findings_count issues found in $file"
            fi
        fi
    done
fi

echo "✅ Scan completed!"
echo "📊 Files scanned: $scanned_files"
echo "🚨 Total findings: $total_findings"

# Générer le résumé pour GitHub
cat >> $GITHUB_STEP_SUMMARY << EOF
# 🛡️ Web Sentinel Security Scan Results

| Metric | Value |
|--------|--------|
| Files Scanned | $scanned_files |
| Total Findings | $total_findings |
| Severity Filter | $WS_SEVERITY_MIN |

## 📋 Scan Details
- **Source Path**: \`$WS_SOURCE_PATH\`
- **Languages**: $WS_LANGUAGES
- **Timestamp**: $(date)

EOF

# Upload SARIF si demandé
if [ "$WS_UPLOAD_SARIF" = "true" ] && [ -f "$SARIF_FILE" ]; then
    echo "📤 Uploading SARIF to GitHub Security tab..."
    # GitHub upload SARIF automatiquement si le fichier existe
    cp "$SARIF_FILE" "$GITHUB_WORKSPACE/web-sentinel.sarif"
fi

# Échouer si des vulnérabilités critiques sont trouvées
if [ "$WS_FAIL_ON_FINDINGS" = "true" ] && [ "$total_findings" -gt 0 ]; then
    echo "❌ Build failed: Security issues detected"
    exit 1
fi

echo "🎉 Web Sentinel scan completed successfully!"