#!/usr/bin/env bash
# Phase 5 : tentative NVSwitch. A = methode du 10/09 (image d'origine, SDK, ppcie_mode False) ;
# B = meme appel apres installation de libnvidia-nscq epinglee a la version du pilote, depuis le
# depot reseau NVIDIA (methode du 19/09). Resultat note tel quel, rien n'est revendique s'il echoue.
set -uo pipefail
export PATH="$HOME/.local/bin:$PATH"
cd "$HOME"
for v in SW_NONCE_A SW_NONCE_B; do
  case "${!v:-}" in
    [0-9a-f][0-9a-f]*) ;;
    *) echo "$v missing or not hex" >&2; exit 4 ;;
  esac
done
USERSITE="$(python3 -c 'import site;print(site.getusersitepackages())')"
echo "=== lspci -nn | grep -i nvswitch ==="
lspci -nn 2>/dev/null | grep -i nvswitch || echo "(no NVSwitch listed by lspci)"
echo
echo "=== nvidia device nodes ==="
ls -l /dev/nvidia* 2>&1
echo
echo "=== fabric manager / nvswitch / cc-ready / persistenced services ==="
systemctl list-units --all --no-pager 2>/dev/null | grep -iE "fabric|nvswitch|cc-ready|persistenced" || echo "(none listed)"
echo
echo "=== NSCQ library on the stock image ==="
dpkg -l 2>/dev/null | grep -i nscq || echo "no nscq package installed"
ls -l /usr/lib/x86_64-linux-gnu/libnvidia-nscq* 2>&1 | head -5
cat > /tmp/nras_switch.py <<'PY'
"""NVSwitch evidence and NRAS switch attestation with nv-attestation-sdk, ppcie_mode=False."""
import base64
import json
import os
import sys
import traceback

NRAS_SWITCH = "https://nras.attestation.nvidia.com/v3/attest/switch"


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  # noqa: F401  (configures the SDK logging)
        from nv_attestation_sdk.nvswitch import attest_nvswitch_remote
    except Exception:
        traceback.print_exc()
        return 3
    print(f"Tenant nonce, drawn outside the VM: {nonce}", flush=True)
    options = {"ppcie_mode": False, "no_gpu_mode": False}
    try:
        evidence = attest_nvswitch_remote.get_evidence(nonce, options) or []
    except Exception:
        traceback.print_exc()
        evidence = []
    print(f"switch evidence items: {len(evidence)}", flush=True)
    ok, token = attest_nvswitch_remote.attest(nonce, evidence, {"verifier_url": NRAS_SWITCH, "claims_version": "2.0"})
    print(f"NRAS switch attestation -> {ok}", flush=True)
    if token:
        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"switch token bytes: {len(text.encode('utf-8'))}", flush=True)
        try:
            summary_jwt, per_switch = token[0][1], token[1]
            print(f"summary {json.dumps(b64json(summary_jwt.split('.')[1]))}", flush=True)
            for sw in sorted(per_switch):
                print(f"{sw} {json.dumps(b64json(per_switch[sw].split('.')[1]))}", flush=True)
        except Exception:
            print("switch token not fully decoded:", flush=True)
            traceback.print_exc()
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
PY
echo
echo "=== A. method of 10 September: switch evidence and NRAS, ppcie_mode False, stock image ==="
sudo rm -f /tmp/nras_switch_a.json /tmp/nras_switch_b.json
timeout 240 sudo env PATH="$PATH" PYTHONPATH="$USERSITE" python3 -u /tmp/nras_switch.py "$SW_NONCE_A" /tmp/nras_switch_a.json 2>&1
echo "exit code: $?"
echo
echo "=== B. same call after installing libnvidia-nscq pinned to the driver (NVIDIA network repository, method of 19 September) ==="
. /etc/os-release
DIST=$(echo "$VERSION_ID" | tr -d .)
PILOTE=$(nvidia-smi --query-gpu=driver_version --format=csv,noheader | head -1)
echo "driver ${PILOTE}, target package libnvidia-nscq=${PILOTE}-1ubuntu1, repository ubuntu${DIST}"
wget -q "https://developer.download.nvidia.com/compute/cuda/repos/ubuntu${DIST}/x86_64/cuda-keyring_1.1-1_all.deb" -O /tmp/cuda-keyring.deb \
  && sudo dpkg -i /tmp/cuda-keyring.deb 2>&1 | tail -2
sudo apt-get -o DPkg::Lock::Timeout=90 update -qq 2>&1 | tail -3
apt-cache policy libnvidia-nscq 2>/dev/null | head -8
sudo DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=90 install -y -q "libnvidia-nscq=${PILOTE}-1ubuntu1" 2>&1 | tail -4
dpkg -l 2>/dev/null | grep -i nscq || echo "libnvidia-nscq NOT installed"
ls -l /usr/lib/x86_64-linux-gnu/libnvidia-nscq* 2>&1 | head -5
timeout 240 sudo env PATH="$PATH" PYTHONPATH="$USERSITE" python3 -u /tmp/nras_switch.py "$SW_NONCE_B" /tmp/nras_switch_b.json 2>&1
echo "exit code: $?"
echo "=== end of phase 5 ==="
