#!/bin/bash
set -euo pipefail

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

cd "$ROOT"

VULN_PREFIX="/tmp/wolfssl-vuln"
FIXED_PREFIX="/tmp/wolfssl-fixed"

if [ ! -f "$VULN_PREFIX/lib/libwolfssl.a" ] || [ ! -f "$FIXED_PREFIX/lib/libwolfssl.a" ]; then
    echo "ERROR: Pre-built wolfSSL libraries not found." >&2
    exit 1
fi

echo "=== Compiling variant test against vulnerable wolfSSL ==="
gcc -g -O0 \
    -I"$VULN_PREFIX/include" \
    -L"$VULN_PREFIX/lib" \
    "$ROOT/vuln_variant/variant_test.c" \
    -lwolfssl -lm \
    -o "$ROOT/vuln_variant/variant_test_vuln" \
    -static

echo "=== Running variant test against vulnerable wolfSSL ==="
"$ROOT/vuln_variant/variant_test_vuln" | tee "$LOGS/variant_vuln_output.txt"
VULN_RESULT=${PIPESTATUS[0]}
echo "Vulnerable version exit code: $VULN_RESULT"

echo ""
echo "=== Compiling variant test against fixed wolfSSL ==="
gcc -g -O0 \
    -I"$FIXED_PREFIX/include" \
    -L"$FIXED_PREFIX/lib" \
    "$ROOT/vuln_variant/variant_test.c" \
    -lwolfssl -lm \
    -o "$ROOT/vuln_variant/variant_test_fixed" \
    -static

echo "=== Running variant test against fixed wolfSSL ==="
"$ROOT/vuln_variant/variant_test_fixed" | tee "$LOGS/variant_fixed_output.txt"
FIXED_RESULT=${PIPESTATUS[0]}
echo "Fixed version exit code: $FIXED_RESULT"

echo ""
echo "=== Summary ==="
echo "Vulnerable version: exit=$VULN_RESULT (0=variant reproduced, 1=not reproduced)"
echo "Fixed version:    exit=$FIXED_RESULT (0=variant reproduced, 1=not reproduced)"

# A true bypass means the variant is reproduced on the FIXED version (exit 0).
# If the variant is NOT reproduced on fixed (exit 1), the fix is effective.
if [ "$FIXED_RESULT" -eq 0 ]; then
    echo "RESULT: BYPASS DETECTED - variant reproduces on fixed version!"
    exit 0
else
    echo "RESULT: NO BYPASS - variant does not reproduce on fixed version."
    exit 1
fi
