#!/usr/bin/env bash
# report — collect Linux hardware + functional outcomes
# and upload to rig-observer (https://github.com/loganwoolf/rig-observer).
#
# Usage:
#   report                 # collect + upload, then offer attestation + suspend test
#   report --dry-run       # print the JSON payload to stdout, upload nothing
#   report --report        # attest component outcomes without asking
#   report --suspend-test  # verified suspend cycle without asking
#   report --url URL       # override API base (default https://rig.observer)
#
# Human-readable progress ("-> stage ... ok (result)") goes to stderr as each
# stage runs. The JSON payload (--dry-run) and the final machine URL go to
# stdout, so `report --dry-run | jq` stays clean.
#
# Every external probe is bounded by timeout(1) and every upload by
# curl --connect-timeout 10 --max-time 60, so a slow tool or dead network
# fails loudly instead of hanging.
#
# Component fixity is reported per part: "fixed" = onboard (matrix material
# for the motherboard), "addin" = owner-slotted (dGPU, add-in wifi / PCIe
# card). Laptops are fixed-config, so all their parts are fixed; on desktops
# and servers, PCI on 00:xx is onboard and PCI behind a root port
# (01:00.0, ...) is owner-slotted.
#
# Environment:
#   RIG_OBSERVER_TOKEN  reuse a specific anonymous reporter token
#   RIG_OBSERVER_URL    same as --url (legacy aliases: LLDB_TOKEN / LLDB_URL)

set -euo pipefail

usage() {
	cat <<'EOF'
report — collect Linux hardware + functional outcomes
and upload to rig-observer.

usage:
  report                 collect + upload, then offer attestation + suspend test
  report --dry-run       print the JSON payload, upload nothing
  report --report        attest component outcomes without asking
  report --suspend-test  verified suspend cycle without asking
  (with a terminal, the default run offers both steps interactively; without
   one — cron, agents, curl|bash — it uploads and prints the machine URL)
  report --url URL       override API base (default https://rig.observer)

environment:
  RIG_OBSERVER_TOKEN   reuse a specific anonymous reporter token
  RIG_OBSERVER_URL     same as --url (legacy: LLDB_TOKEN / LLDB_URL)
EOF
}

API_URL="${RIG_OBSERVER_URL:-${LLDB_URL:-https://rig.observer}}"
DRY_RUN=0
DO_REPORT=0
SUSPEND_TEST=0
TOKEN="${RIG_OBSERVER_TOKEN:-${LLDB_TOKEN:-}}"

while [ $# -gt 0 ]; do
	case "$1" in
	--dry-run) DRY_RUN=1 ;;
	--report) DO_REPORT=1 ;;
	--suspend-test) SUSPEND_TEST=1 ;;
	--url)
		[ -n "${2:-}" ] || { echo "error: --url needs an argument" >&2; exit 64; }
		API_URL="$2"
		shift
		;;
	-h | --help)
		usage
		exit 0
		;;
	*)
		usage >&2
		echo "error: unknown option: $1" >&2
		exit 64
		;;
	esac
	shift
done

# ---- helpers -----------------------------------------------------------------

jesc() {
	# escape for JSON string: backslash, quote, newline/tab
	printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | tr -d '\n\r\t'
}

have() { command -v "$1" >/dev/null 2>&1; }

tmo() {
	# tmo SECS CMD… — bound every external probe with timeout(1) when available
	if have timeout; then
		timeout "$@"
	else
		shift
		"$@"
	fi
}

# ---- progress lines (stderr only) ----------------------------------------------
# Each stage prints its label BEFORE the underlying work runs and its result
# after:  -> probing PCI components ... ok (5 found)
# Plain ASCII; simple ANSI colors only when stderr is a terminal.

if [ -t 2 ]; then
	C_CYN=$'\033[36m'
	C_GRN=$'\033[32m'
	C_RED=$'\033[31m'
	C_OFF=$'\033[0m'
else
	C_CYN=""
	C_GRN=""
	C_RED=""
	C_OFF=""
fi

stage() { printf '%s-> %s ...%s ' "$C_CYN" "$1" "$C_OFF" >&2; }
stage_ok() { printf '%sok%s (%s)\n' "$C_GRN" "$C_OFF" "$1" >&2; }
stage_done() { printf '%sdone%s (%s)\n' "$C_GRN" "$C_OFF" "$1" >&2; }
stage_info() { printf '%s\n' "$1" >&2; }
stage_fail() { printf '%s%s%s\n' "$C_RED" "$1" "$C_OFF" >&2; }

# post_json URL PAYLOAD [extra curl args…]
# Sets POST_CODE / POST_BODY; returns 0 only for HTTP 2xx. On any failure it
# prints the curl error or HTTP status + response body to stderr instead of
# dying silently.
post_json() {
	local url="$1" payload="$2"
	shift 2
	local code body_file err_file
	body_file=$(mktemp)
	err_file=$(mktemp)
	POST_CODE=000
	POST_BODY=""
	code=$(curl -sS --connect-timeout 10 --max-time 60 \
		-X POST -H "Content-Type: application/json" "$@" \
		--data "$payload" --output "$body_file" --write-out '%{http_code}' \
		"$url" 2>"$err_file") || {
		local err
		err=$(cat "$err_file")
		rm -f "$body_file" "$err_file"
		printf 'error: POST %s failed: %s\n' "$url" "${err:-network error}" >&2
		return 1
	}
	rm -f "$err_file"
	POST_CODE="$code"
	POST_BODY=$(cat "$body_file")
	rm -f "$body_file"
	case "$POST_CODE" in
	2*) return 0 ;;
	*)
		printf 'error: POST %s -> HTTP %s: %s\n' "$url" "$POST_CODE" "${POST_BODY:0:400}" >&2
		return 1
		;;
	esac
}

# ---- identity ----------------------------------------------------------------

DMI=/sys/class/dmi/id
stage "reading DMI identity"
BOARD_VENDOR=$(cat "$DMI/board_vendor" 2>/dev/null || echo unknown)
BOARD_NAME=$(cat "$DMI/board_name" 2>/dev/null || echo unknown)
PRODUCT_NAME=$(cat "$DMI/product_name" 2>/dev/null || echo)
BIOS_VERSION=$(cat "$DMI/bios_version" 2>/dev/null || echo)

CHASSIS=Notebook
case "$(cat "$DMI/chassis_type" 2>/dev/null || echo 9)" in
1 | 2 | 3) CHASSIS=Desktop ;;
8 | 9 | 10 | 14) CHASSIS=Notebook ;;
31 | 32) CHASSIS=Server ;;
*) CHASSIS=Other ;;
esac

# DMI placeholders ("System Product Name" & friends) mean "custom build";
# the motherboard is the real identity then. Same rule for laptops, but their
# product_name is normally the marketing name so the fallback rarely fires.
case "$(printf '%s' "$PRODUCT_NAME" | tr '[:upper:]' '[:lower:]')" in
"" | "system product name" | "to be filled by o.e.m." | "default string" | "not specified" | "unknown" | "none")
	PRODUCT_NAME=""
	;;
esac
case "$(printf '%s' "$BOARD_VENDOR" | tr '[:upper:]' '[:lower:]')" in
"asustek computer inc.") BOARD_VENDOR="ASUS" ;;
"micro-star international co., ltd.") BOARD_VENDOR="MSI" ;;
"gigabyte technology co., ltd.") BOARD_VENDOR="Gigabyte" ;;
"hewlett-packard") BOARD_VENDOR="HP" ;;
"lenovo") BOARD_VENDOR="Lenovo" ;;
esac

DMI_TXT="$BOARD_VENDOR $BOARD_NAME"
if [ -n "$PRODUCT_NAME" ] && [ "$PRODUCT_NAME" != "$BOARD_NAME" ]; then
	DMI_TXT+=" / $PRODUCT_NAME"
fi
stage_ok "$DMI_TXT ($CHASSIS)"

# distro detection (Omarchy first-class)
stage "detecting distro"
DISTRO=""
DISTRO_VERSION=""
OMARCHY=0
if have omarchy || tmo 5 pacman -Q omarchy >/dev/null 2>&1; then
	OMARCHY=1
	DISTRO=omarchy
	DISTRO_VERSION=$(tmo 5 pacman -Q omarchy 2>/dev/null | awk '{print $2}')
fi
if [ -z "$DISTRO" ] && [ -r /etc/os-release ]; then
	# shellcheck disable=SC1091
	. /etc/os-release
	DISTRO="${ID:-}"
	DISTRO_VERSION="${VERSION_ID:-}"
fi
if [ -n "$DISTRO" ]; then
	D_TXT="$DISTRO"
	[ -n "$DISTRO_VERSION" ] && D_TXT+=" $DISTRO_VERSION"
	[ "$OMARCHY" = 1 ] && D_TXT+=" (Omarchy)"
	stage_ok "$D_TXT"
else
	stage_fail "unknown distro"
fi

# kernel / DE / cmdline
stage "reading kernel and cmdline"
KERNEL=$(uname -r)
CMDLINE=$(cat /proc/cmdline 2>/dev/null || echo)
DE="${XDG_CURRENT_DESKTOP:-}"
if [ "$OMARCHY" = 1 ] && have hyprctl; then DE="Hyprland"; fi

# known kernel flavors: which non-stock kernel packages are installed
KERNEL_FORK=""
if have pacman; then
	for pkg in linux-surface linux-tuxedo linux-cachyos linux-zen linux-lts linux-hardened; do
		if tmo 5 pacman -Q "$pkg" >/dev/null 2>&1; then
			KERNEL_FORK="$KERNEL_FORK $pkg"
		fi
	done
	KERNEL_FORK="${KERNEL_FORK# }"
fi

K_TXT="kernel $KERNEL"
[ -n "$KERNEL_FORK" ] && K_TXT+=" (fork pkgs: $KERNEL_FORK)"
[ -n "$DE" ] && K_TXT+=", DE $DE"
stage_ok "$K_TXT"

stage "reading CPU model"
CPU=""
if have lscpu; then
	CPU=$(tmo 10 lscpu 2>/dev/null | grep "Model name" | sed -E 's/^[^:]+:\s*//' | sed -E 's/\s+-\s+.*//' || true)
fi
if [ -z "$CPU" ]; then
	CPU=$(grep -m1 "model name" /proc/cpuinfo 2>/dev/null | sed 's/.*: //' || true)
fi
if [ -n "$CPU" ]; then
	stage_ok "$CPU"
else
	stage_info "unknown"
fi

# ---- sleep capabilities --------------------------------------------------------

stage "checking sleep states"
MEM_SLEEP=$(cat /sys/power/mem_sleep 2>/dev/null || echo)
POWER_STATES=$(cat /sys/power/state 2>/dev/null || echo)
S3=0
case "$MEM_SLEEP" in *deep*) S3=1 ;; esac
S4=0
case "$POWER_STATES" in *disk*) S4=1 ;; esac
S0IX="" # detection requires acpidump; left for the web report if known

# display "[s2idle] deep" as "s2idle [deep]" so the selected state is obvious
MEM_SLEEP_DISP="${MEM_SLEEP:-n/a}"
if [ -n "$MEM_SLEEP" ]; then
	MEM_SLEEP_DISP=$(printf '%s' "$MEM_SLEEP" | sed -E 's/^(\[[^]]+\])[[:space:]]+(.+)$/\2 \1/')
fi
S3_TXT=no
[ "$S3" = 1 ] && S3_TXT=yes
S4_TXT=no
[ "$S4" = 1 ] && S4_TXT=yes
stage_info "$MEM_SLEEP_DISP, S3 $S3_TXT, S4 $S4_TXT"

# ---- components ----------------------------------------------------------------

declare -a COMPONENTS_JSON=()

add_component() { # type bus vendor device subsystem name driver attachment fixity
	local json="{\"type\":\"$(jesc "$1")\""
	[ -n "${2:-}" ] && json+=",\"bus\":\"$(jesc "$2")\""
	[ -n "${3:-}" ] && json+=",\"vendor_id\":\"$(jesc "$3")\""
	[ -n "${4:-}" ] && json+=",\"device_id\":\"$(jesc "$4")\""
	[ -n "${5:-}" ] && json+=",\"subsystem_id\":\"$(jesc "$5")\""
	[ -n "${6:-}" ] && json+=",\"name\":\"$(jesc "$6")\""
	[ -n "${7:-}" ] && json+=",\"driver\":\"$(jesc "$7")\""
	[ -n "${8:-}" ] && json+=",\"attachment\":\"$(jesc "$8")\""
	[ -n "${9:-}" ] && json+=",\"fixity\":\"$(jesc "$9")\""
	json+="}"
	COMPONENTS_JSON+=("$json")
}

stage "probing PCI components"
PCI_COUNT=0
if have lspci; then
	while IFS= read -r line; do
		addr="${line%% *}"
		rest="${line#* }"
		cls="$(printf '%s' "$rest" | sed -E 's/^([^[]+) \[[0-9a-f]{4}\]: .*/\1/')"
		ids="$(printf '%s' "$rest" | grep -oE '\[[0-9a-f]{4}:[0-9a-f]{4}\]' | tr -d '[]' | tr ':' ' ')"
		vendor=$(printf '%s' "$ids" | awk '{print $1}')
		device=$(printf '%s' "$ids" | awk '{print $2}')
		name="$(printf '%s' "$rest" | sed -E 's/^[^]]*\]: //' | sed -E 's/\[[0-9a-f]{4}:[0-9a-f]{4}\]//; s/\s*\(rev [^)]*\)//; s/\s+$//')"
		driver=$(tmo 10 lspci -k -s "$addr" 2>/dev/null | grep "Kernel driver in use" | sed 's/.*: //' || true)
		subsys=$(tmo 10 lspci -k -s "$addr" 2>/dev/null | grep -oE 'Subsystem: .*\[[0-9a-f]{4}:[0-9a-f]{4}\]' | grep -oE '\[[0-9a-f]{4}:[0-9a-f]{4}\]$' | tr -d '[]' || true)
		case "$cls" in
		*"VGA compatible"* | *"3D controller"* | *"Display controller"*) type=graphics ;;
		*"Network controller"*) type=wifi ;;
		*"Ethernet controller"*) type=ethernet ;;
		*"Audio"*) type=audio ;;
		*"SD Host"* | *"SD/MMC"*) type=sd_reader ;;
		*) continue ;;
		esac
		# fixity: laptops are fixed-config, everything onboard. Desktops and
		# others: PCI on 00:xx sits on the board; anything behind a PCIe root
		# port (01:00.0, 02:00.0, ...) is a slotted card -> owner hardware.
		if [ "$CHASSIS" = "Notebook" ]; then
			fixity=fixed
		else
			case "$addr" in
			00:*) fixity=fixed ;;
			*) fixity=addin ;;
			esac
		fi
		add_component "$type" "pci" "$vendor" "$device" "${subsys:-}" "$name" "$driver" "" "$fixity"
		PCI_COUNT=$((PCI_COUNT + 1))
	done < <(tmo 15 lspci -nn 2>/dev/null | grep -E "VGA compatible|3D controller|Display controller|Network controller|Ethernet controller|Audio|SD Host|SD/MMC")
	stage_ok "$PCI_COUNT found"
else
	stage_info "lspci not installed"
fi

stage "probing USB components"
USB_COUNT=0
if have lsusb; then
	while IFS= read -r line; do
		ids="$(printf '%s' "$line" | grep -oE '^[0-9a-f]{4}:[0-9a-f]{4}' || true)"
		vendor="${ids%%:*}"
		device="${ids##*:}"
		name="$(printf '%s' "$line" | sed -E 's/^[0-9a-f]{4}:[0-9a-f]{4} //' | sed -E 's/^[0-9a-f]+ [0-9a-f]+ //')"
		case "$name" in
		*Webcam* | *Camera* | *"HD Video"*) type=webcam ;;
		*Fingerprint*) type=fingerprint ;;
		*Bluetooth*) type=bluetooth ;;
		*Wireless* | *Wi-Fi*) type=wifi ;;
		*Touchpad*) type=touchpad ;;
		*Keyboard*) type=keyboard ;;
		*Audio* | *Sound* | *Speaker*) type=audio ;;
		*) continue ;;
		esac
		# attachment heuristic: internal combos (webcam/fingerprint/touchpad/
		# keyboard/BT-half-of-combo-card) vs plugged-in peripherals (USB wifi
		# dongles, USB audio interfaces, external keyboards). Desktops: all
		# USB is peripheral. Laptops: known-internal types marked internal,
		# ambiguous ones (USB wifi/audio) left unknown for attestation.
		att=""
		if [ "$CHASSIS" = "Notebook" ]; then
			case "$type" in
			webcam | fingerprint | touchpad | keyboard | bluetooth) att="internal" ;;
			esac
		else
			att="external"
		fi
		add_component "$type" "usb" "$vendor" "$device" "" "$name" "" "$att" ""
		USB_COUNT=$((USB_COUNT + 1))
	done < <(tmo 15 lsusb 2>/dev/null)
	stage_ok "$USB_COUNT found"
else
	stage_info "lsusb not installed"
fi

# dedupe identical type+bus+vendor+device entries
if [ "${#COMPONENTS_JSON[@]}" -gt 0 ]; then
	mapfile -t COMPONENTS_JSON < <(printf '%s\n' "${COMPONENTS_JSON[@]}" | awk '!seen[$0]++')
fi

# ---- payload -------------------------------------------------------------------

stage "assembling payload"

COMPONENTS=$(printf '%s,' "${COMPONENTS_JSON[@]}" | sed 's/,$//')
ALIASES=""
if [ -n "$PRODUCT_NAME" ] && [ "$PRODUCT_NAME" != "$BOARD_NAME" ]; then
	ALIASES=",\"aliases\":[\"$(jesc "$PRODUCT_NAME")\"]"
fi

SLEEP_JSON=""
if [ -n "$MEM_SLEEP" ] || [ "$S3" = 1 ] || [ "$S4" = 1 ]; then
	SLEEP_JSON=",\"sleep\":{\"mem_sleep\":\"$(jesc "$MEM_SLEEP")\""
	[ -n "$S0IX" ] && SLEEP_JSON+=",\"s0ix\":$S0IX"
	SLEEP_JSON+=",\"s3\":$S3,\"s4\":$S4}"
fi

PAYLOAD="{
  \"schema\": 1,
  \"collected_at\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",
  \"laptop\": {
    \"board_vendor\": \"$(jesc "$BOARD_VENDOR")\",
    \"board_name\": \"$(jesc "$BOARD_NAME")\",
    \"product_name\": \"$(jesc "$PRODUCT_NAME")\"${ALIASES},
    \"chassis\": \"$(jesc "$CHASSIS")\"
  },
  \"system\": {
    \"distro\": \"$(jesc "$DISTRO")\",
    \"distro_version\": \"$(jesc "$DISTRO_VERSION")\",
    \"kernel\": \"$(jesc "$KERNEL")\",
    \"de\": \"$(jesc "$DE")\",
    \"bios\": \"$(jesc "$BIOS_VERSION")\",
    \"cpu\": \"$(jesc "$CPU")\",
    \"cmdline\": \"$(jesc "$CMDLINE")\"
  }${SLEEP_JSON},
  \"components\": [$COMPONENTS]
}"

stage_ok "${#COMPONENTS_JSON[@]} components"

if [ "$DRY_RUN" = 1 ]; then
	printf '%s\n' "$PAYLOAD"
	exit 0
fi

# ---- token ---------------------------------------------------------------------

# state moved to rig-observer/; migrate tokens from the old
# rig-observer-report/ path so existing devices keep their identity
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}"
TOKEN_DIR="$DATA_DIR/rig-observer"
mkdir -p "$TOKEN_DIR"
TOKEN_FILE="$TOKEN_DIR/token"
OLD_TOKEN_FILE="$DATA_DIR/rig-observer-report/token"

if [ -z "$TOKEN" ]; then
	if [ -r "$TOKEN_FILE" ]; then
		stage "loading reporter token"
		TOKEN=$(cat "$TOKEN_FILE")
		stage_ok "stored in $TOKEN_FILE"
	elif [ -r "$OLD_TOKEN_FILE" ]; then
		stage "migrating reporter token"
		TOKEN=$(cat "$OLD_TOKEN_FILE")
		if [ -n "$TOKEN" ]; then
			mv "$OLD_TOKEN_FILE" "$TOKEN_FILE"
			rmdir "$DATA_DIR/rig-observer-report" 2>/dev/null || true
			stage_ok "$TOKEN_FILE (from $OLD_TOKEN_FILE)"
		fi
	fi
fi

if [ -z "$TOKEN" ]; then
	stage "minting anonymous reporter token"
	if ! post_json "$API_URL/api/reporters" ""; then
		stage_fail "cannot continue without a token (see error above)"
		exit 1
	fi
	TOKEN=$(printf '%s' "$POST_BODY" | sed -E 's/.*"token":"([^"]+)".*/\1/')
	if [ -z "$TOKEN" ]; then
		stage_fail "no token in response"
		exit 1
	fi
	printf '%s' "$TOKEN" >"$TOKEN_FILE"
	stage_done "saved to $TOKEN_FILE"
fi

# ---- upload ---------------------------------------------------------------------

stage "uploading probe to $API_URL"
if ! post_json "$API_URL/api/probes" "$PAYLOAD" -H "Authorization: Bearer $TOKEN"; then
	stage_fail "upload failed (see error above; run --dry-run to inspect the payload)"
	exit 1
fi

MACHINE_ID=$(printf '%s' "$POST_BODY" | sed -nE 's/.*"machine_id": ?([0-9]+).*/\1/p')
if [ -z "$MACHINE_ID" ]; then
	MACHINE_ID=$(printf '%s' "$POST_BODY" | sed -nE 's/.*"laptop_id": ?([0-9]+).*/\1/p')
fi
DISPLAY_NAME=$(printf '%s' "$POST_BODY" | sed -nE 's/.*"display_name": ?"([^"]*)".*/\1/p')
[ -n "$DISPLAY_NAME" ] || DISPLAY_NAME="machine #$MACHINE_ID"
MACHINE_URL="$API_URL/laptops/$MACHINE_ID"
stage_done "machine #$MACHINE_ID ($DISPLAY_NAME)"

# ---- attestation + verified suspend (functions; called after upload) ---------------

# friendly duplicate handling: the dedupe rule blocks exact repeats
# (same token/machine/component/context/kernel); say so instead of alarming
report_note() {
	if [ "${POST_CODE:-}" = "409" ]; then
		printf '  already reported for this kernel + context — skipped\n' >&2
		printf '  (a kernel bump or changed setup creates a new report)\n' >&2
	else
		printf '  NOT reported (see error above)\n' >&2
	fi
}

do_attestation() {
	echo >&2
	echo "Attesting outcomes per component (everything this machine exposes):" >&2
	echo "  w = works   — fully functional, including sleep/resume" >&2
	echo "  p = partial — usable with caveats or workarounds" >&2
	echo "  b = broken  — does not function" >&2
	echo "  Enter = skip" >&2
	echo >&2

	# rows: id type bus attachment fixity name — parsed from the probe response
	# (stable key order); ids/names are the server's, not our local payload.
	# fixity is optional so pre-fixity API responses still parse.
	declare -a ROWS=()
	while IFS= read -r row; do
		[ -z "$row" ] && continue
		ROWS+=("$row")
	done < <(printf '%s' "$POST_BODY" | grep -oE '"id":[0-9]+,"type":"[^"]*","bus":"[^"]*","attachment":"[^"]*"(,"fixity":"[^"]*")?(,"name":"[^"]*")?' | sed -E 's/"id":([0-9]+),"type":"([^"]*)","bus":"([^"]*)","attachment":"([^"]*)"(,"fixity":"([^"]*)")?(,"name":"(.*)")?/\1 \2 \3 \4 \6 \8/')

	local total=${#ROWS[@]}
	if [ "$total" = 0 ]; then
		echo "no components to attest (probe returned none)" >&2
		return 0
	fi

	local n=0
	for row in "${ROWS[@]}"; do
		n=$((n + 1))
		read -r cid ctype cbus catt cfix cname <<<"$row"
		# vendor:device for the prompt comes from our payload (same order as
		# the response); fall back gracefully if they drift apart
		vd="$(printf '%s' "${COMPONENTS_JSON[$((n - 1))]:-}" | sed -nE 's/.*"vendor_id":"([^"]*)","device_id":"([^"]*)".*/\1:\2/p')"
		[ -z "$vd" ] && vd="?"

		# progress + full component identity before every prompt
		if [ "$cfix" = "addin" ]; then
			printf '[%d/%d] -> %s · %s (%s %s, add-in)\n' "$n" "$total" "$ctype" "${cname:-name unknown}" "$cbus" "$vd" >&2
		else
			printf '[%d/%d] -> %s · %s (%s %s)\n' "$n" "$total" "$ctype" "${cname:-name unknown}" "$cbus" "$vd" >&2
		fi

		# unknown-attachment USB parts: is this built in, or plugged in?
		if [ "$cbus" = "usb" ] && [ "$catt" = "unknown" ]; then
			printf '  built in or plugged in? [b = built-in, e = external, Enter=skip]: ' >&2
			read -r ans </dev/tty || ans=""
			case "$ans" in
			b | B) att="internal" ;;
			e | E) att="external" ;;
			*) echo "  left unknown (excluded from the rig matrix until attested)" >&2; continue ;;
			esac
			if post_json "$API_URL/api/components/$cid" "{\"attachment\":\"$att\"}" \
				-H "Authorization: Bearer $TOKEN" -H "X-Source: tool"; then
				printf '  ok -> %s marked %s\n' "$ctype" "$att" >&2
			else
				report_note
			fi
		fi
		printf '  outcome [w/p/b, Enter=skip]: ' >&2
		read -r ans </dev/tty || ans=""
		case "$ans" in
		w | W) outcome=works ;;
		p | P) outcome=partial ;;
		b | B) outcome=broken ;;
		*) echo "  skipped" >&2; continue ;;
		esac
		printf '  note (Enter = none): ' >&2
		read -r note </dev/tty || note=""
		R_BODY="{\"laptop_id\":$MACHINE_ID,\"component_id\":$cid,\"outcome\":\"$outcome\",\"context\":\"normal\",\"kernel\":\"$(jesc "$KERNEL")\",\"distro\":\"$(jesc "$DISTRO")\",\"distro_version\":\"$(jesc "$DISTRO_VERSION")\",\"de\":\"$(jesc "$DE")\",\"bios\":\"$(jesc "$BIOS_VERSION")\",\"note\":\"$(jesc "$note")\"}"
		if post_json "$API_URL/api/reports" "$R_BODY" \
			-H "Authorization: Bearer $TOKEN" -H "X-Source: tool"; then
			printf '  ok -> reported %s: %s\n' "$ctype" "$outcome" >&2
		else
			report_note
		fi
	done
}

do_suspend_test() {
	echo >&2
	echo "Suspend test: suspends this machine for ~10 seconds, then reports the" >&2
	echo "wake outcome to $API_URL. Close work first!" >&2
	printf 'Proceed? [y/N] ' >&2
	read -r ans </dev/tty || ans=y
	case "$ans" in
	y | Y) ;;
	*) echo "skipped suspend test" >&2; return 0 ;;
	esac

	stage "capturing driver state"
	DRIVERS_BEFORE=$(tmo 10 lspci -k 2>/dev/null | grep "Kernel driver in use" | sort || true)
	stage_ok "$(printf '%s\n' "$DRIVERS_BEFORE" | grep -c . || true) drivers bound"

	echo "Suspending now (~10 s)..." >&2
	stage "running suspend cycle"
	if tmo 60 systemctl suspend; then
		stage_done "resumed"
	else
		stage_fail "systemctl suspend exited nonzero; checking aftermath"
	fi

	# give wifi/bluetooth a moment to reassociate after wake
	echo "waiting for wifi/bluetooth to reassociate..." >&2
	sleep 5
	DRIVERS_AFTER=$(tmo 10 lspci -k 2>/dev/null | grep "Kernel driver in use" | sort || true)
	RESUME_ERRORS=$(tmo 10 journalctl -k --since "-2 minutes" 2>/dev/null | grep -iE "resume|suspend|failed|error" | tail -5 || true)

	LOST=$(comm -23 <(printf '%s\n' "$DRIVERS_BEFORE") <(printf '%s\n' "$DRIVERS_AFTER") | tr '\n' ';' | sed 's/;$//')
	if [ -n "$LOST" ]; then
		SUS_OUTCOME=broken
		SUS_NOTE="drivers lost after resume: $LOST"
	elif [ -n "$RESUME_ERRORS" ]; then
		SUS_OUTCOME=partial
		SUS_NOTE="resume completed with kernel errors (see journal)"
	else
		SUS_OUTCOME=works
		SUS_NOTE="suspend + resume clean; all drivers rebound"
	fi
	stage_info "suspend test: $SUS_OUTCOME — $SUS_NOTE"

	SUS_BODY="{\"laptop_id\":$MACHINE_ID,\"outcome\":\"$SUS_OUTCOME\",\"context\":\"after_suspend\",\"kernel\":\"$(jesc "$KERNEL")\",\"distro\":\"$(jesc "$DISTRO")\",\"de\":\"$(jesc "$DE")\",\"bios\":\"$(jesc "$BIOS_VERSION")\",\"note\":\"$(jesc "$SUS_NOTE")\"}"
	if post_json "$API_URL/api/reports" "$SUS_BODY" \
		-H "Authorization: Bearer $TOKEN" -H "X-Source: tool"; then
		echo "ok -> reported suspend result (source: verified tool run)" >&2
	else
		report_note
	fi
}

# ---- one-pass follow-ups -------------------------------------------------------------

# a terminal attached (even with stdin piped, as in curl|bash) -> offer steps
INTERACTIVE=0
if [ -t 0 ] || [ -t 1 ] || [ -t 2 ]; then
	INTERACTIVE=1
fi

if [ "$DO_REPORT" = 1 ]; then
	do_attestation
elif [ "$INTERACTIVE" = 1 ]; then
	printf 'Attest component outcomes now? [Y/n] ' >&2
	read -r ans </dev/tty || ans=""
	case "$ans" in
	n | N) echo "skipped — rerun with --report later" >&2 ;;
	*) do_attestation ;;
	esac
else
	printf 'attest outcomes: rerun with --report in a terminal\n' >&2
fi

if [ "$SUSPEND_TEST" = 1 ]; then
	do_suspend_test
elif [ "$INTERACTIVE" = 1 ]; then
	printf 'Run the verified suspend test? [y/N] ' >&2
	read -r ans </dev/tty || ans=""
	case "$ans" in
	y | Y) do_suspend_test ;;
	*) echo "skipped — rerun with --suspend-test later" >&2 ;;
	esac
fi

# final stdout line: the machine page, named
printf 'machine: %s — %s\n' "$DISPLAY_NAME" "$MACHINE_URL"
