#!/usr/bin/env bash
# Build usbboot (rpiboot) on THIS machine (e.g. Fedora) and deploy to the Proxmox host.
# Use this when the host has no internet. Requires: dnf (Fedora) or apt (Debian/Ubuntu), git, ssh to host.
# Usage: ./build-and-deploy-usbboot-to-host.sh [proxmox_host]
# Example: ./build-and-deploy-usbboot-to-host.sh root@10.130.60.224

set -e
PROXMOX="${1:-root@10.130.60.224}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="/tmp/usbboot-build-$$"
cleanup() { rm -rf "$BUILD_DIR"; }
trap cleanup EXIT

echo "[$(date -Iseconds)] Building usbboot for host $PROXMOX ..."

# Install build deps (Fedora or Debian/Ubuntu)
if command -v dnf &>/dev/null; then
  echo "Installing build deps (dnf)..."
  sudo dnf install -y git libusb1-devel pkg-config glibc-devel gcc gcc-c++ make
elif command -v apt-get &>/dev/null; then
  echo "Installing build deps (apt)..."
  sudo apt-get update -qq
  sudo DEBIAN_FRONTEND=noninteractive apt-get install -y git libusb-1.0-0-dev pkg-config build-essential
else
  echo "Error: need dnf or apt-get to install dependencies."
  exit 1
fi

mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"
echo "Cloning usbboot (with submodules)..."
git clone --recurse-submodules --shallow-submodules --depth=1 https://github.com/raspberrypi/usbboot
cd usbboot
echo "Building..."
make

# Deploy: binary + gadget dir(s) to host /opt/usbboot
echo "[$(date -Iseconds)] Deploying to $PROXMOX:/opt/usbboot ..."
ssh "$PROXMOX" "mkdir -p /opt/usbboot"
rsync -a "$BUILD_DIR/usbboot/rpiboot" "$PROXMOX:/opt/usbboot/"
# CM4 needs mass-storage-gadget (64-bit); copy whichever exists
for dir in mass-storage-gadget64 mass-storage-gadget; do
  if [[ -d "$BUILD_DIR/usbboot/$dir" ]]; then
    rsync -a "$BUILD_DIR/usbboot/$dir/" "$PROXMOX:/opt/usbboot/$dir/"
    echo "  Copied $dir/"
  fi
done
ssh "$PROXMOX" "chmod +x /opt/usbboot/rpiboot"

# Verify gadget has boot files (rpiboot needs bootfiles.bin or bootcode*.bin)
if ! ssh "$PROXMOX" "test -f /opt/usbboot/mass-storage-gadget64/bootfiles.bin || test -f /opt/usbboot/mass-storage-gadget64/boot.img" 2>/dev/null; then
  echo "Warning: mass-storage-gadget64 may be missing boot files. If rpiboot fails with 'No bootcode files found', run: ./populate-gadget-on-host.sh $PROXMOX"
fi

echo "[$(date -Iseconds)] usbboot deployed to $PROXMOX:/opt/usbboot"
echo "Ensure the host flash script runs rpiboot with: -d /opt/usbboot/mass-storage-gadget64 (or mass-storage-gadget)."
