#!/bin/sh
# Rescue script: mount eMMC root and chroot to run rpi-eeprom-config.
# Use this when stuck in network-only boot (BOOT_ORDER=0x2) to set BOOT_ORDER=0x1 or 0x21.
# Run from the initramfs rescue shell (after booting with provisioning_rescue=1 in cmdline).

set -e
ROOT="/mnt/emmc"
BOOT="$ROOT/boot/firmware"
[ -d "$ROOT/boot" ] && [ ! -d "$BOOT" ] && BOOT="$ROOT/boot"

echo "=== Mounting eMMC for EEPROM config ==="
# CM4 / reTerminal: eMMC is usually mmcblk0, p1=boot (FAT), p2=root (ext4)
if [ ! -b /dev/mmcblk0p2 ]; then
  echo "No /dev/mmcblk0p2 found. Try: ls /dev/mmcblk*"
  exit 1
fi

mkdir -p "$ROOT"
mount /dev/mmcblk0p2 "$ROOT" || { echo "Mount root failed"; exit 1; }
if [ -b /dev/mmcblk0p1 ]; then
  mkdir -p "$BOOT"
  mount /dev/mmcblk0p1 "$BOOT" 2>/dev/null || true
fi
mount -t proc none "$ROOT/proc"
mount -t sysfs none "$ROOT/sys"
mount --bind /dev "$ROOT/dev"
mount --bind /dev/pts "$ROOT/dev/pts" 2>/dev/null || true

if [ -x "$ROOT/usr/bin/rpi-eeprom-config" ]; then
  echo "Chroot to eMMC and run: rpi-eeprom-config --edit"
  echo "Set BOOT_ORDER=0x1 (eMMC only) or 0x21 (network first, then eMMC), save, then exit and run: reboot"
  chroot "$ROOT" /usr/bin/rpi-eeprom-config --edit
else
  echo "rpi-eeprom-config not found in eMMC. Chrooting anyway; run: apt install rpi-eeprom && rpi-eeprom-config --edit"
  chroot "$ROOT" /bin/sh -i
fi
