#!/bin/sh
# autopkgtest: smoke-test the INSTALLED `proximo` command.
#
# This never talks to a real Proxmox host. It points PROXIMO_API_BASE_URL at
# a loopback port nothing listens on, so the connection is refused
# immediately -- `proximo doctor` is designed to treat that as a reported
# preflight finding, not a crash, and still print its full JSON report. The
# assertion is that the bundled dh-virtualenv venv starts, the imports
# resolve, and `doctor` runs its real code path: the report comes out, names
# the unreachable plane, and exits 4, the shell door's status for it.
set -e

WORKDIR="$(mktemp -d)"
trap 'rm -rf "$WORKDIR"' EXIT

# Syntactically plausible token file (USER@REALM!TOKENID=SECRET). `doctor`'s
# connectivity check fails before any token content would be sent anywhere;
# this only has to look like a token file, never a real one.
printf '%s\n' \
    'smoke@pve!autopkgtest=0000000000000000000000000000000000000000000000000000000000000000' \
    > "$WORKDIR/token"
chmod 600 "$WORKDIR/token"   # the core refuses a token file anything else on the box can read

OUT="$WORKDIR/stdout"
ERR="$WORKDIR/stderr"

# PROXIMO_ENV_FILE=/nonexistent: don't let a real ~/.config/proximo/proximo.env
# on the testbed leak in and override what this test is checking.
set +e
env \
    PROXIMO_ENV_FILE=/nonexistent \
    PROXIMO_AUDIT_LOG="$WORKDIR/audit.log" \
    PROXIMO_API_BASE_URL='https://127.0.0.1:1/api2/json' \
    PROXIMO_TOKEN_PATH="$WORKDIR/token" \
    /usr/bin/proximo doctor >"$OUT" 2>"$ERR"
rc=$?
set -e

echo "== proximo doctor exit status: $rc =="
echo "== stdout =="
cat "$OUT"
echo "== stderr =="
cat "$ERR"

# The real assertion: doctor's JSON report came out on stdout and names the
# unreachable plane (the core doctor, src/proximo/core/doctor.py: the vendor's
# own GET /version, failed with the connection error). The exit status is the
# shell door's contract: 4 = a configured plane unreachable. Silence, a
# traceback, or any other status means the binary did not do its job.
head -n 1 "$OUT" | grep -q '^{$' || {
    echo "FAIL: proximo doctor did not print a JSON report (no opening '{')" >&2
    exit 1
}

grep -q '"doctor": "proximo-core"' "$OUT" || {
    echo "FAIL: proximo doctor's JSON report is missing its \"doctor\" header field" >&2
    exit 1
}

grep -q '"error": "ConnectError"' "$OUT" || {
    echo "FAIL: proximo doctor did not report the (expected) unreachable plane" >&2
    exit 1
}

[ "$rc" -eq 4 ] || {
    echo "FAIL: proximo doctor exited $rc, not 4 (a configured plane unreachable)" >&2
    exit 1
}

echo "PASS: proximo doctor ran the real code path against an unreachable plane and printed its JSON report"
