#!/bin/bash
set -euo pipefail

ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
VULN_DIR="$ROOT/vuln_variant"
REPO_DIR="$ROOT/external/temporal"
mkdir -p "$LOGS"
mkdir -p "$VULN_DIR"

echo "[+] Temporal Server CVE-2026-5199 Variant Analysis"
echo "[+] Root: $ROOT"

if [ ! -d "$REPO_DIR/.git" ]; then
    echo "[-] Repository not found at $REPO_DIR"
    exit 1
fi

# Copy the variant test into the repo's batcher package
TEST_FILE="$VULN_DIR/variant_test.go"
TARGET_FILE="$REPO_DIR/service/worker/batcher/variant_test.go"

cp "$TEST_FILE" "$TARGET_FILE"

cd "$REPO_DIR"

# Save original state and restore on exit
ORIGINAL_REF=$(git rev-parse HEAD)
restore_repo() {
    git checkout -q "$ORIGINAL_REF" || true
    rm -f "$TARGET_FILE"
}
trap restore_repo EXIT

# Make sure both tags are available
if ! git rev-parse v1.29.4 >/dev/null 2>&1 || ! git rev-parse v1.29.5 >/dev/null 2>&1; then
    echo "[+] Fetching required tags..."
    git fetch --depth=200 origin tag v1.29.4 tag v1.29.5
fi

# Helper to run tests at a specific ref
run_variant_tests() {
    local ref="$1"
    local logfile="$2"

    echo "[+] Running variant tests at $ref..."
    git checkout -q "$ref"
    # Ensure the test file is present after checkout
    cp "$TEST_FILE" "$TARGET_FILE"

    cd "$REPO_DIR/service/worker/batcher"
    go test -v -run '^TestVariant_' -timeout 120s . > "$logfile" 2>&1 || true
    cd "$REPO_DIR"
}

# Run on vulnerable version
run_variant_tests "v1.29.4" "$LOGS/variant_v1.29.4.log"

# Run on fixed version
run_variant_tests "v1.29.5" "$LOGS/variant_v1.29.5.log"

# Analyze results
VULN_BYPASSED=$(grep -c 'BYPASSED' "$LOGS/variant_v1.29.4.log" 2>/dev/null)
FIX_BYPASSED=$(grep -c 'BYPASSED' "$LOGS/variant_v1.29.5.log" 2>/dev/null)
# grep -c exits 1 with no matches and produces empty output, so default to 0
VULN_BYPASSED=${VULN_BYPASSED:-0}
FIX_BYPASSED=${FIX_BYPASSED:-0}

echo ""
echo "[+] Results summary:"
echo "    v1.29.4 (vulnerable): bypassed=$VULN_BYPASSED"
echo "    v1.29.5 (fixed):      bypassed=$FIX_BYPASSED"

# Determine if any variant bypassed the fixed version
if [ "$FIX_BYPASSED" -gt 0 ]; then
    echo "[-] VARIANT BYPASS FOUND on fixed version!"
    exit 0
else
    echo "[+] No variant bypassed the fixed version."
    echo "[+] The patch closes all tested alternate triggers."
    exit 1
fi
