#!/bin/bash
# Synor Security Audit Script
# Run this script to perform automated security checks
#
# Usage: ./scripts/security-audit.sh [--full]
#   --full: Also run cargo geiger (slow) and outdated checks

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
FULL_SCAN=false

if [[ "$1" == "--full" ]]; then
    FULL_SCAN=true
fi

cd "$PROJECT_ROOT"

echo "=========================================="
echo "Synor Security Audit"
echo "=========================================="
echo "Date: $(date)"
echo "Commit: $(git rev-parse --short HEAD 2>/dev/null || echo 'N/A')"
echo ""

# ============================================================================
# 1. Vulnerability Scan
# ============================================================================
echo "=== 1. VULNERABILITY SCAN ==="
if command -v cargo-audit &> /dev/null; then
    cargo audit --deny warnings || echo "⚠️  Vulnerabilities found!"
else
    echo "⚠️  cargo-audit not installed. Install with: cargo install cargo-audit"
    echo "    Skipping vulnerability scan..."
fi
echo ""

# ============================================================================
# 2. License & Security Policy
# ============================================================================
echo "=== 2. LICENSE & SECURITY POLICY ==="
if command -v cargo-deny &> /dev/null; then
    cargo deny check 2>&1 || echo "⚠️  Policy violations found!"
else
    echo "⚠️  cargo-deny not installed. Install with: cargo install cargo-deny"
    echo "    Skipping policy check..."
fi
echo ""

# ============================================================================
# 3. Clippy Static Analysis
# ============================================================================
echo "=== 3. STATIC ANALYSIS (clippy) ==="
cargo clippy --all-targets --all-features -- \
    -D clippy::unwrap_used \
    -D clippy::panic \
    -D clippy::expect_used \
    -W clippy::pedantic \
    2>&1 | head -50 || echo "⚠️  Clippy warnings found!"
echo ""

# ============================================================================
# 4. Check for Secrets
# ============================================================================
echo "=== 4. SECRET DETECTION ==="
echo "Scanning for potential secrets..."

# Common secret patterns
PATTERNS=(
    "API_KEY"
    "SECRET_KEY"
    "PRIVATE_KEY"
    "PASSWORD"
    "aws_access_key"
    "aws_secret_key"
    "-----BEGIN PRIVATE KEY-----"
    "-----BEGIN RSA PRIVATE KEY-----"
)

FOUND_SECRETS=false
for pattern in "${PATTERNS[@]}"; do
    if grep -rn --include="*.rs" --include="*.ts" --include="*.js" \
       --include="*.json" --include="*.toml" --include="*.env*" \
       "$pattern" . 2>/dev/null | grep -v "target/" | grep -v ".git/" | head -5; then
        FOUND_SECRETS=true
    fi
done

if [ "$FOUND_SECRETS" = true ]; then
    echo "⚠️  Potential secrets found! Review the above matches."
else
    echo "✅ No obvious secrets detected"
fi
echo ""

# ============================================================================
# 5. Unsafe Code Detection
# ============================================================================
echo "=== 5. UNSAFE CODE DETECTION ==="
if [ "$FULL_SCAN" = true ] && command -v cargo-geiger &> /dev/null; then
    cargo geiger --output-format Ratio 2>&1 | head -30
else
    # Quick unsafe detection without cargo-geiger
    UNSAFE_COUNT=$(grep -rn "unsafe" --include="*.rs" . 2>/dev/null | grep -v "target/" | grep -v ".git/" | wc -l)
    echo "Found $UNSAFE_COUNT lines containing 'unsafe'"
    if [ "$UNSAFE_COUNT" -gt 0 ]; then
        echo "Unsafe usage locations:"
        grep -rn "unsafe" --include="*.rs" . 2>/dev/null | grep -v "target/" | grep -v ".git/" | head -10
    fi
fi
echo ""

# ============================================================================
# 6. Outdated Dependencies
# ============================================================================
if [ "$FULL_SCAN" = true ]; then
    echo "=== 6. OUTDATED DEPENDENCIES ==="
    if command -v cargo-outdated &> /dev/null; then
        cargo outdated --root-deps-only 2>&1 | head -30
    else
        echo "⚠️  cargo-outdated not installed. Install with: cargo install cargo-outdated"
    fi
    echo ""
fi

# ============================================================================
# 7. Property Tests
# ============================================================================
echo "=== 7. PROPERTY TESTS ==="
echo "Running property-based tests..."
cargo test --release proptest -- --nocapture 2>&1 | tail -20 || echo "⚠️  Some property tests failed!"
echo ""

# ============================================================================
# Summary
# ============================================================================
echo "=========================================="
echo "Security Audit Complete"
echo "=========================================="
echo ""
echo "Recommendations:"
echo "  1. Review any findings above"
echo "  2. Run with --full flag for complete analysis"
echo "  3. Consider fuzzing critical paths with cargo-fuzz"
echo "  4. Submit findings to security@synor.cc"
