#!/usr/bin/env bash
# Run on the Proxmox HOST (root) when the host has internet.
# Builds usbboot (rpiboot) and installs to /opt/usbboot so the auto-flash can run.
# If the host has no internet, run build-and-deploy-usbboot-to-host.sh from your Fedora machine instead.

set -e
apt-get update
apt-get install -y libusb-1.0-0-dev git pkg-config build-essential
cd /tmp
rm -rf usbboot
git clone --recurse-submodules --shallow-submodules --depth=1 https://github.com/raspberrypi/usbboot
cd usbboot
make
mkdir -p /opt/usbboot
cp rpiboot /opt/usbboot/
# Copy gadget dir(s) so rpiboot -d works
for dir in mass-storage-gadget64 mass-storage-gadget; do
  [[ -d "$dir" ]] && cp -a "$dir" /opt/usbboot/
done
echo "usbboot installed at /opt/usbboot/rpiboot"

# If rpiboot later fails with "No bootcode files" (broken symlinks in gadget), fix-gadget repairs it.
# Run it now; prefer copy in /opt (from deploy) or in deploy dir.
for fix in /opt/cm4-provisioning/fix-gadget-bootcode-on-host.sh /tmp/emmc-provisioning-deploy/scripts/fix-gadget-bootcode-on-host.sh; do
  if [[ -f "$fix" ]]; then
    echo "Running fix-gadget-bootcode-on-host.sh to ensure gadget has valid boot files..."
    bash "$fix" || true
    break
  fi
done
