#!/usr/bin/env bash
# Populate /opt/usbboot/mass-storage-gadget64 on the Proxmox host (no rpiboot build).
# Use when rpiboot works but you see "No 'bootcode' files found" — the gadget dir is empty.
# Usage: ./populate-gadget-on-host.sh [proxmox_host]
# Example: ./populate-gadget-on-host.sh root@10.130.60.224

set -e
PROXMOX="${1:-root@10.130.60.224}"
BUILD_DIR="/tmp/usbboot-gadget-$$"
cleanup() { rm -rf "$BUILD_DIR"; }
trap cleanup EXIT

echo "[$(date -Iseconds)] Cloning usbboot to fetch mass-storage-gadget64 ..."
mkdir -p "$BUILD_DIR"
git clone --depth=1 https://github.com/raspberrypi/usbboot "$BUILD_DIR/usbboot"

GADGET="$BUILD_DIR/usbboot/mass-storage-gadget64"
if [[ ! -d "$GADGET" ]]; then
  echo "Error: mass-storage-gadget64 not found in clone."
  exit 1
fi
# rpiboot needs at least bootfiles.bin or bootcode*.bin
if [[ ! -f "$GADGET/bootfiles.bin" && ! -f "$GADGET/boot.img" ]]; then
  echo "Warning: clone has no bootfiles.bin or boot.img. Trying git lfs pull..."
  (cd "$BUILD_DIR/usbboot" && git lfs pull 2>/dev/null) || true
fi
if [[ ! -f "$GADGET/bootfiles.bin" && ! -f "$GADGET/boot.img" ]]; then
  echo "Error: mass-storage-gadget64 still has no boot files. Install git-lfs and retry, or run build-and-deploy-usbboot-to-host.sh for a full deploy."
  exit 1
fi

echo "[$(date -Iseconds)] Syncing mass-storage-gadget64 to $PROXMOX:/opt/usbboot/ ..."
ssh "$PROXMOX" "mkdir -p /opt/usbboot"
rsync -a "$GADGET/" "$PROXMOX:/opt/usbboot/mass-storage-gadget64/"
echo "Done. Verify with: ssh $PROXMOX 'ls -la /opt/usbboot/mass-storage-gadget64/'"
