#!/usr/bin/env bash
# Manually test rpiboot on the Proxmox host (device in boot mode must be connected).
# Usage:
#   From your machine:  ./test-usbboot-on-host.sh [proxmox_host]
#   On the host:        ./test-usbboot-on-host.sh
#   With timeout (e.g. 60s): TIMEOUT=60 ./test-usbboot-on-host.sh root@100.106.128.36
#   If you see "Failed to write correct length, returned -7", try USB 2.0 port or add delay:
#   RPIBOOT_EXTRA_OPTS='-m 2000' ./test-usbboot-on-host.sh root@100.106.128.36
#
# Replace proxmox_host with your host, e.g. root@100.106.128.36

set -e
HOST="${1:-}"
RPIBOOT="${RPIBOOT:-/opt/usbboot/rpiboot}"
GADGET="${GADGET:-/opt/usbboot/mass-storage-gadget64}"
TIMEOUT="${TIMEOUT:-0}"
RPIBOOT_EXTRA_OPTS="${RPIBOOT_EXTRA_OPTS:-}"

run_on_host() {
  if [[ -n "$HOST" ]]; then
    ssh "$HOST" "$@"
  else
    "$@"
  fi
}

echo "=== Checking usbboot and gadget on ${HOST:-localhost} ==="
run_on_host "test -x $RPIBOOT" || { echo "Error: $RPIBOOT not found or not executable"; exit 1; }
run_on_host "test -d $GADGET" || { echo "Error: $GADGET not found"; exit 1; }
run_on_host "test -f $GADGET/bootcode4.bin || test -f $GADGET/boot.img || test -f $GADGET/bootfiles.bin" || { echo "Error: no boot file in $GADGET"; exit 1; }
echo "  rpiboot: $RPIBOOT"
echo "  gadget:  $GADGET"
echo ""

echo "=== USB devices (2b8e / 0a5c:2711 = CM4 boot mode) ==="
run_on_host "lsusb | grep -E '2b8e|0a5c' || echo '  None. Connect reTerminal with eMMC disable jumper and USB slave port.'"
echo ""

echo "=== Tip: if rpiboot fails with 'Failed to write correct length, returned -7', use a USB 2.0 port, or run: RPIBOOT_EXTRA_OPTS='-m 2000' $0 $* ==="
echo ""

echo "=== Running rpiboot (verbose) — connect device now if not already ==="
echo "  When the device switches to mass storage, rpiboot will exit and a new /dev/sdX may appear."
echo "  Use Ctrl+C to stop, or wait for exit."
echo ""

RPIBOOT_CMD="$RPIBOOT -v -d $GADGET $RPIBOOT_EXTRA_OPTS"
if [[ -n "$HOST" ]]; then
  if [[ "$TIMEOUT" -gt 0 ]]; then
    ssh "$HOST" "timeout $TIMEOUT $RPIBOOT_CMD" || true
  else
    ssh -t "$HOST" "$RPIBOOT_CMD" || true
  fi
else
  if [[ "$TIMEOUT" -gt 0 ]]; then
    timeout "$TIMEOUT" $RPIBOOT_CMD || true
  else
    $RPIBOOT_CMD || true
  fi
fi

echo ""
echo "=== Block devices now (check for new /dev/sdX) ==="
run_on_host "lsblk -nd -o NAME,SIZE,TYPE /dev/sd[a-z] 2>/dev/null || true"
