#!/usr/bin/env bash
# Phase 3 : attestation NVIDIA (NRAS) des 8 GPU, methode du 10/09/2026 (nv-attestation-sdk,
# get_evidence(options={"ppcie_mode": False})), sur un nonce tire HORS de la VM (variable NONCE).
set -uo pipefail
export PATH="$HOME/.local/bin:$PATH"
cd "$HOME"
case "${NONCE:-}" in
  [0-9a-f][0-9a-f]*) ;;
  *) echo "NONCE missing or not hex" >&2; exit 4 ;;
esac
USERSITE="$(python3 -c 'import site;print(site.getusersitepackages())')"
cat > /tmp/nras_8gpu.py <<'PY'
"""8-GPU NRAS attestation, method of 10 September 2026, tenant nonce from the command line."""
import base64
import inspect
import json
import os
import sys
import traceback

NRAS_GPU = "https://nras.attestation.nvidia.com/v3/attest/gpu"
OCSP = "https://ocsp.ndis.nvidia.com/"
RIM = "https://rim.attestation.nvidia.com/v1/rim/"


def b64json(segment):
    segment += "=" * (-len(segment) % 4)
    return json.loads(base64.urlsafe_b64decode(segment.encode("ascii")))


def main():
    nonce, out = sys.argv[1], sys.argv[2]
    try:
        from nv_attestation_sdk import attestation
    except Exception:
        traceback.print_exc()
        return 3
    cls = attestation.Attestation
    print("=== SDK signatures ===", flush=True)
    for name in ("get_evidence", "attest", "add_verifier", "set_nonce"):
        try:
            print(f"{name:<13}{inspect.signature(getattr(cls, name))}", flush=True)
        except Exception as err:
            print(f"{name:<13}? ({err})", flush=True)
    print("=== NRAS ATTESTATION ppcie_mode=False (not standalone) (gpu) ===", flush=True)
    print(f"Tenant nonce, drawn outside the VM: {nonce}", flush=True)
    try:
        client = cls()
        client.set_name("voltagegpu-8xh200-proof")
        client.set_nonce(nonce)
        client.set_claims_version("2.0")
        client.add_verifier(attestation.Devices.GPU, attestation.Environment.REMOTE, NRAS_GPU, "",
                            ocsp_url=OCSP, rim_url=RIM)
        evidence = client.get_evidence(options={"ppcie_mode": False})
        print(f"evidence items: {len(evidence)}", flush=True)
        ok = client.attest(evidence)
        print(f"attest(evidence) -> {ok}", flush=True)
        token = client.get_token()
    except Exception:
        traceback.print_exc()
        return 2
    text = token if isinstance(token, str) else json.dumps(token)
    with open(out, "w", encoding="utf-8") as fh:
        fh.write(text)
    os.chmod(out, 0o644)
    print(f"token bytes: {len(text.encode('utf-8'))}", flush=True)
    try:
        eat = json.loads(text)
        sdk_jwt = b64json(eat[0][1].split(".")[1])
        print("SDK envelope JWT (made locally by the SDK, HS256, not NVIDIA-signed):",
              json.dumps({k: sdk_jwt.get(k) for k in ("iss", "iat")}), flush=True)
        for verifier, value in eat[1].items():
            summary_jwt, per_gpu = value[0][1], value[1]
            print(f"{verifier} summary header {json.dumps(b64json(summary_jwt.split('.')[0]))}", flush=True)
            print(f"{verifier} summary {json.dumps(b64json(summary_jwt.split('.')[1]))}", flush=True)
            for gpu in sorted(per_gpu):
                print(f"{verifier} {gpu} {json.dumps(b64json(per_gpu[gpu].split('.')[1]))}", flush=True)
    except Exception:
        print("token not fully decoded:", flush=True)
        traceback.print_exc()
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
PY
sudo rm -f /tmp/nras_token.json
sudo env PATH="$PATH" PYTHONPATH="$USERSITE" python3 -u /tmp/nras_8gpu.py "$NONCE" /tmp/nras_token.json 2>&1
echo "exit code: $?"
echo "=== end of phase 3 ==="
