#!/usr/bin/env bash
# Populate /srv/tftpboot with Raspberry Pi 4 / CM4 boot files from the official firmware repo.
# Run inside the LXC (as root), or from your machine: ./populate-tftpboot-from-git.sh root@10.130.60.141
# Requires: curl or wget, tar; the LXC must have internet (eth0).

set -e
TARGET="${1:-}"
FIRMWARE_URL="https://github.com/raspberrypi/firmware/archive/refs/heads/master.tar.gz"
TFTP_ROOT="${TFTP_ROOT:-/srv/tftpboot}"

do_populate() {
  echo "Populating $TFTP_ROOT from Raspberry Pi firmware (GitHub) ..."
  mkdir -p "$TFTP_ROOT"
  if [[ -f "$TFTP_ROOT/start4cd.elf" ]]; then
    echo "start4cd.elf already present; skipping download (remove it to re-fetch)."
    return 0
  fi
  if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
    echo "Installing curl ..."
    apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq curl
  fi
  local tmpdir
  tmpdir=$(mktemp -d)
  trap "rm -rf $tmpdir" EXIT
  if command -v curl >/dev/null 2>&1; then
    curl -sL "$FIRMWARE_URL" -o "$tmpdir/firmware.tar.gz"
  else
    wget -q -O "$tmpdir/firmware.tar.gz" "$FIRMWARE_URL"
  fi
  tar xzf "$tmpdir/firmware.tar.gz" -C "$tmpdir"
  if [[ ! -d "$tmpdir/firmware-master/boot" ]]; then
    echo "Error: boot folder not found in archive"
    exit 1
  fi
  cp -a "$tmpdir/firmware-master/boot/." "$TFTP_ROOT/"
  echo "Copied boot files to $TFTP_ROOT ($(ls "$TFTP_ROOT" | wc -l) items)."
  ls -la "$TFTP_ROOT"/start4*.elf "$TFTP_ROOT"/fixup4*.dat "$TFTP_ROOT"/config.txt 2>/dev/null || true
}

if [[ -n "$TARGET" ]]; then
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  scp "$SCRIPT_DIR/populate-tftpboot-from-git.sh" "$TARGET:/tmp/populate-tftpboot.sh"
  ssh "$TARGET" "bash /tmp/populate-tftpboot.sh"
  exit 0
fi

do_populate
