#!/usr/bin/env bash
# Run on the Proxmox HOST to see provisioning status, USB, flash job, and logs.
# Usage: ./monitor-from-host.sh   or: ssh root@10.130.60.224 'bash -s' < scripts/monitor-from-host.sh

PROV=/var/lib/cm4-provisioning

echo "═══════════════════════════════════════════════════════════════"
echo "  CM4 provisioning – host monitor"
echo "═══════════════════════════════════════════════════════════════"
echo ""

echo "--- USB (CM4 boot mode: 2b8e or 0a5c:2711) ---"
lsusb | grep -E "2b8e|0a5c" || echo "  No CM4 boot device seen."
echo ""

echo "--- Current status (dashboard reads this) ---"
if [[ -f "$PROV/status.json" ]]; then
  cat "$PROV/status.json" | python3 -m json.tool 2>/dev/null || cat "$PROV/status.json"
else
  echo "  No status.json (no run yet)."
fi
echo ""

echo "--- Flash job (systemd unit) ---"
systemctl show cm4-flash-once --property=ActiveState,SubState,ExecMainPID 2>/dev/null || echo "  Unit not run yet."
echo ""

echo "--- Last 20 lines of flash.log ---"
tail -20 "$PROV/flash.log" 2>/dev/null || echo "  No flash.log"
echo ""

echo "--- Provisioning dir ---"
ls -la "$PROV/" 2>/dev/null || echo "  Dir missing."
echo ""

echo "--- Block devices (eMMC appears here after rpiboot) ---"
lsblk -d -o NAME,SIZE,MODEL,TRAN 2>/dev/null | head -15
echo ""

echo "--- Config ---"
echo "  enabled:  $([ -f /etc/cm4-provisioning/enabled ] && echo yes || echo no)"
echo "  rpiboot:  $([ -x /opt/usbboot/rpiboot ] && echo /opt/usbboot/rpiboot || echo MISSING)"
echo "  golden:   $([ -f $PROV/golden.img ] && echo present || echo not set)"
echo "  backups:  $(ls "$PROV/backups" 2>/dev/null | wc -l) file(s)"
