#!/bin/bash
set -euo pipefail

# Portable paths - works from any directory
ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
VULN_VARIANT_DIR="$ROOT/vuln_variant"

mkdir -p "$LOGS"
mkdir -p "$VULN_VARIANT_DIR/logs"

echo "=========================================="
echo "CVE-2026-5463 Variant Analysis Script"
echo "=========================================="
echo ""
echo "Testing variant injection paths:"
echo "  1. Module options injection (original - line 2299)"
echo "  2. Payload options injection (variant - line 2316)"
echo ""

# Ensure Python dependencies
echo "[1/4] Installing Python dependencies..."
pip install -q msgpack requests retry 2>/dev/null || true

# Install vulnerable pymetasploit3 from local source
echo "[2/4] Installing vulnerable pymetasploit3 v1.0.6..."
cd "$ROOT/pymetasploit3"
pip install -q -e . 2>/dev/null || pip install -e .

# Run the variant tests
echo ""
echo "[3/4] Running variant reproduction tests..."
cd "$ROOT"

# Set environment variables for the test
export REPRO_LOG_DIR="$LOGS"
export VULN_VARIANT_LOG_DIR="$VULN_VARIANT_DIR/logs"
export PYMSF_DIR="$ROOT/pymetasploit3"

python3 "$VULN_VARIANT_DIR/variant_tests.py" 2>&1 | tee "$VULN_VARIANT_DIR/logs/variant_output.log"
VARIANT_EXIT_CODE=${PIPESTATUS[0]}

echo ""
echo "[4/4] Results:"

# Analyze results
if [ -f "$VULN_VARIANT_DIR/logs/variant_manifest.json" ]; then
    echo "  Variant test completed"
    echo "  Exit code: $VARIANT_EXIT_CODE"
    echo ""
    echo "  Evidence files:"
    ls -la "$VULN_VARIANT_DIR/logs/" 2>/dev/null || echo "    (no logs found)"
    echo ""
    
    # Check if variant was confirmed
    if grep -q '"variant_confirmed": true' "$VULN_VARIANT_DIR/logs/"*.json 2>/dev/null; then
        echo "  [SUCCESS] Variant injection path CONFIRMED"
        echo "  Payload options injection works as variant bypass"
        exit 0
    else
        echo "  [INFO] Variant testing completed - see logs for details"
        # Exit 1 since this is a bypass attempt on unpatched code
        # We expect this to work since no patch exists yet
        exit 1
    fi
else
    echo "  [FAIL] Could not generate variant manifest"
    exit 1
fi
