#!/bin/bash
set -euo pipefail

# Portable root detection - works anywhere
ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
mkdir -p "$LOGS"

cd "$ROOT"

# Check for pre-installed wolfSSL builds
VULN_PREFIX="/tmp/wolfssl-vuln"
FIXED_PREFIX="/tmp/wolfssl-fixed"

# If not pre-installed, build them
if [ ! -f "$VULN_PREFIX/lib/libwolfssl.a" ] || [ ! -f "$FIXED_PREFIX/lib/libwolfssl.a" ]; then
    echo "Building wolfSSL vulnerable and fixed versions..."
    
    # Ensure source directories exist
    if [ ! -d "$ROOT/external/wolfssl-vuln" ] || [ ! -d "$ROOT/external/wolfssl-fixed" ]; then
        echo "Cloning wolfSSL repositories..."
        rm -rf "$ROOT/external/wolfssl-vuln" "$ROOT/external/wolfssl-fixed"
        git clone --depth=1 --branch v5.9.0-stable https://github.com/wolfSSL/wolfssl.git "$ROOT/external/wolfssl-vuln" || true
        git clone --depth=1 --branch v5.9.1-stable https://github.com/wolfSSL/wolfssl.git "$ROOT/external/wolfssl-fixed" || true
    fi
    
    # Build vulnerable version
    if [ ! -f "$VULN_PREFIX/lib/libwolfssl.a" ]; then
        echo "Building vulnerable wolfSSL v5.9.0-stable..."
        cd "$ROOT/external/wolfssl-vuln"
        ./autogen.sh
        ./configure --enable-chacha --enable-poly1305 --enable-aesgcm --enable-opensslextra \
            --disable-shared --enable-static --enable-debug \
            CFLAGS='-g -O0' --prefix="$VULN_PREFIX"
        make -j"$(nproc)"
        make install
    fi
    
    # Build fixed version
    if [ ! -f "$FIXED_PREFIX/lib/libwolfssl.a" ]; then
        echo "Building fixed wolfSSL v5.9.1-stable..."
        cd "$ROOT/external/wolfssl-fixed"
        ./autogen.sh
        ./configure --enable-chacha --enable-poly1305 --enable-aesgcm --enable-opensslextra \
            --disable-shared --enable-static --enable-debug \
            CFLAGS='-g -O0' --prefix="$FIXED_PREFIX"
        make -j"$(nproc)"
        make install
    fi
fi

cd "$ROOT"

# Compile test program against both versions
echo "Compiling test program against vulnerable wolfSSL..."
gcc "$ROOT/repro/aead_tag_check.c" \
    -I"$VULN_PREFIX/include" -L"$VULN_PREFIX/lib" \
    -lwolfssl -lpthread -lm -o "$LOGS/aead-vuln"

echo "Compiling test program against fixed wolfSSL..."
gcc "$ROOT/repro/aead_tag_check.c" \
    -I"$FIXED_PREFIX/include" -L"$FIXED_PREFIX/lib" \
    -lwolfssl -lpthread -lm -o "$LOGS/aead-fixed"

# Run tests and capture output
echo "Running vulnerable build test..."
"$LOGS/aead-vuln" > "$LOGS/vulnerable_output.txt" 2>&1 || true

echo "Running fixed build test..."
"$LOGS/aead-fixed" > "$LOGS/fixed_output.txt" 2>&1 || true

# Parse concrete evidence from outputs
VULN_T1_FINAL=$(grep -A2 "Test 1: Zeroed tag" "$LOGS/vulnerable_output.txt" | grep "EVP_DecryptFinal_ex ret=" | sed 's/.*ret=//' | awk '{print $1}')
VULN_T2_FINAL=$(grep -A2 "Test 2: Random bad tag" "$LOGS/vulnerable_output.txt" | grep "EVP_DecryptFinal_ex ret=" | sed 's/.*ret=//' | awk '{print $1}')
VULN_T3_FINAL=$(grep -A2 "Test 3: Flipped ciphertext" "$LOGS/vulnerable_output.txt" | grep "EVP_DecryptFinal_ex ret=" | sed 's/.*ret=//' | awk '{print $1}')

FIXED_T1_FINAL=$(grep -A2 "Test 1: Zeroed tag" "$LOGS/fixed_output.txt" | grep "EVP_DecryptFinal_ex ret=" | sed 's/.*ret=//' | awk '{print $1}')
FIXED_T2_FINAL=$(grep -A2 "Test 2: Random bad tag" "$LOGS/fixed_output.txt" | grep "EVP_DecryptFinal_ex ret=" | sed 's/.*ret=//' | awk '{print $1}')
FIXED_T3_FINAL=$(grep -A2 "Test 3: Flipped ciphertext" "$LOGS/fixed_output.txt" | grep "EVP_DecryptFinal_ex ret=" | sed 's/.*ret=//' | awk '{print $1}')

# Write runtime manifest
cat > "$LOGS/runtime_manifest.json" <<EOF
{
  "cve_id": "CVE-2026-5479",
  "vulnerable_version": "wolfSSL v5.9.0-stable",
  "fixed_version": "wolfSSL v5.9.1-stable",
  "test_program": "repro/aead_tag_check.c",
  "api_under_test": "wolfSSL_EVP_CipherFinal (ChaCha20-Poly1305 decrypt path)",
  "tamper_strategies": [
    "zeroed_authentication_tag",
    "random_authentication_tag",
    "flipped_ciphertext_byte_with_correct_tag"
  ],
  "vulnerable_results": {
    "test1_zeroed_tag": {
      "EVP_DecryptFinal_ex_return": $VULN_T1_FINAL,
      "behavior": "accepted_forged_tag"
    },
    "test2_random_tag": {
      "EVP_DecryptFinal_ex_return": $VULN_T2_FINAL,
      "behavior": "accepted_forged_tag"
    },
    "test3_modified_ciphertext": {
      "EVP_DecryptFinal_ex_return": $VULN_T3_FINAL,
      "behavior": "accepted_modified_ciphertext"
    }
  },
  "fixed_results": {
    "test1_zeroed_tag": {
      "EVP_DecryptFinal_ex_return": $FIXED_T1_FINAL,
      "behavior": "rejected_forged_tag"
    },
    "test2_random_tag": {
      "EVP_DecryptFinal_ex_return": $FIXED_T2_FINAL,
      "behavior": "rejected_forged_tag"
    },
    "test3_modified_ciphertext": {
      "EVP_DecryptFinal_ex_return": $FIXED_T3_FINAL,
      "behavior": "rejected_modified_ciphertext"
    }
  }
}
EOF

# Validate results
echo ""
echo "=== Validation ==="
echo "Vulnerable build EVP_DecryptFinal_ex returns: T1=$VULN_T1_FINAL T2=$VULN_T2_FINAL T3=$VULN_T3_FINAL"
echo "Fixed build EVP_DecryptFinal_ex returns:      T1=$FIXED_T1_FINAL T2=$FIXED_T2_FINAL T3=$FIXED_T3_FINAL"

if [ "$VULN_T1_FINAL" = "1" ] && [ "$VULN_T2_FINAL" = "1" ] && [ "$VULN_T3_FINAL" = "1" ] && \
   [ "$FIXED_T1_FINAL" = "0" ] && [ "$FIXED_T2_FINAL" = "0" ] && [ "$FIXED_T3_FINAL" = "0" ]; then
    echo ""
    echo "VERDICT: CONFIRMED - CVE-2026-5479 successfully reproduced."
    echo "  - Vulnerable build (v5.9.0): EVP_DecryptFinal_ex returns success (1) for all 3 tampered inputs"
    echo "  - Fixed build (v5.9.1): EVP_DecryptFinal_ex returns failure (0) for all 3 tampered inputs"
    echo "  - Runtime manifest written to: $LOGS/runtime_manifest.json"
    exit 0
else
    echo ""
    echo "VERDICT: FAILED - Could not reproduce expected behavior."
    exit 1
fi
