#!/usr/bin/env bash
# Install rpi-eeprom-config and pieeprom.bin on the LXC (or host) where the dashboard runs.
# Required for "Update EEPROM" from the dashboard when a device is connected via USB boot.
# Run on the LXC: bash -s < scripts/install-eeprom-tools-on-lxc.sh
# Or: ssh root@<LXC-IP> 'bash -s' < emmc-provisioning/scripts/install-eeprom-tools-on-lxc.sh

set -e
RPI_EEPROM_RAW="https://raw.githubusercontent.com/raspberrypi/rpi-eeprom/master"
EEPROM_DIR="${EEPROM_DIR:-/opt/cm4-provisioning/eeprom}"

echo "Installing EEPROM tools to $EEPROM_DIR"

if ! command -v python3 >/dev/null 2>&1; then
  echo "ERROR: Python 3 is required to run rpi-eeprom-config. Install it (e.g. apt install python3) and re-run."
  exit 1
fi

if command -v curl >/dev/null 2>&1; then
  GET="curl -sL"
  GET_O="curl -sL -o"
elif command -v wget >/dev/null 2>&1; then
  GET="wget -q -O -"
  GET_O="wget -q -O"
else
  echo "ERROR: curl or wget required"
  exit 1
fi

mkdir -p "$EEPROM_DIR"
echo "Downloading rpi-eeprom-config..."
$GET_O "$EEPROM_DIR/rpi-eeprom-config" "$RPI_EEPROM_RAW/rpi-eeprom-config"
$GET_O "$EEPROM_DIR/rpi-eeprom-digest" "$RPI_EEPROM_RAW/rpi-eeprom-digest"
chmod +x "$EEPROM_DIR/rpi-eeprom-config" "$EEPROM_DIR/rpi-eeprom-digest"

LATEST_FW=$($GET "https://api.github.com/repos/raspberrypi/rpi-eeprom/contents/firmware-2711/default" \
  | grep -o '"name" *: *"pieeprom-[^"]*\.bin"' | sed 's/"name" *: *"//;s/"//' | sort | tail -1)
if [ -z "$LATEST_FW" ]; then
  echo "WARNING: Could not determine latest firmware from GitHub API. Try again or download pieeprom.bin manually."
else
  $GET_O "$EEPROM_DIR/pieeprom.bin" "$RPI_EEPROM_RAW/firmware-2711/default/$LATEST_FW"
fi

if [ ! -s "$EEPROM_DIR/pieeprom.bin" ]; then
  echo "ERROR: pieeprom.bin is missing or empty"
  exit 1
fi

echo "Verifying rpi-eeprom-config..."
if ! python3 "$EEPROM_DIR/rpi-eeprom-config" "$EEPROM_DIR/pieeprom.bin" >/dev/null 2>&1; then
  echo "WARNING: rpi-eeprom-config could not read pieeprom.bin (non-fatal)"
fi

echo "Done. EEPROM tools installed to $EEPROM_DIR"
