#!/usr/bin/env bash
set -euo pipefail

action="${1:-plan}"
rpi_host="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
rpi_user="${LAB_RPI_USER:-${LAB_RASPBERRY_USER:-jv}}"
rpi_key="${LAB_RPI_SSH_KEY_PATH:-${LAB_RASPBERRY_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}}"
server_ip="${LAB_RPI4_NETBOOT_SERVER_IP:-${LAB_DEBIAN_LAN_IP:-192.168.100.73}}"
tftp_root="${LAB_RPI4_TFTP_ROOT:-/opt/homelab-provisioning/tftp}"
nfs_root="${LAB_RPI4_NFS_ROOT:-/srv/nfs/rpi4}"

case "${action}" in
    plan)
        cat <<EOF
RPi4 NFS staging plan
=====================
source: ${rpi_user}@${rpi_host}
server: ${server_ip}
TFTP root: ${tftp_root}
NFS root: ${nfs_root}

This copies the current RPi4 boot and root filesystems into a per-device
network-root tree. It does not erase the SD card or reboot the Pi.
EOF
        ;;
    apply)
        [[ "${2:-}" == "--yes" ]] || { echo "Use: scripts/rpi4-nfs-stage apply --yes" >&2; exit 2; }
        command -v ssh >/dev/null || { echo "ssh is required" >&2; exit 1; }
        ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" true
        serial="$(ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" "awk '/^Serial/{print \$3}' /proc/cpuinfo | tail -1 | cut -c9-16")"
        [[ "${serial}" =~ ^[0-9a-fA-F]{8}$ ]] || { echo "Unable to determine RPi4 serial prefix" >&2; exit 1; }
        boot_dir="${tftp_root}/${serial}"
        sudo apt-get update
        sudo apt-get install -y nfs-kernel-server rsync
        sudo mkdir -p "${boot_dir}" "${nfs_root}/${serial}"
        ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" 'sudo tar -C /boot/firmware -cf - .' | sudo tar -C "${boot_dir}" -xf -
        ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" 'sudo tar -C / --exclude=./proc --exclude=./sys --exclude=./dev --exclude=./run --exclude=./tmp --exclude=./mnt --exclude=./media --exclude=./boot --exclude=./var/lib/docker --exclude=./nvme-storage --exclude=./lost+found -cf - .' | sudo tar -C "${nfs_root}/${serial}" -xf -
        sudo sed -i -E "s#root=[^ ]+#root=/dev/nfs nfsroot=${server_ip}:${nfs_root}/${serial},vers=4.1,proto=tcp,rw#" "${boot_dir}/cmdline.txt"
        grep -q "${nfs_root}/${serial}" "${boot_dir}/cmdline.txt" || { echo "Failed to set NFS root cmdline" >&2; exit 1; }
        export_line="${nfs_root}/${serial} ${rpi_host}(rw,sync,no_subtree_check,no_root_squash)"
        sudo grep -Fqx "${export_line}" /etc/exports 2>/dev/null || echo "${export_line}" | sudo tee -a /etc/exports >/dev/null
        sudo exportfs -ra
        sudo systemctl enable --now nfs-server 2>/dev/null || sudo systemctl enable --now nfs-kernel-server
        echo "NFS staging prepared for RPi4 serial ${serial}."
        echo "The Pi still boots from SD until its EEPROM boot order is changed to network-first."
        ;;
    *)
        echo "Usage: scripts/rpi4-nfs-stage {plan|apply --yes}" >&2
        exit 2
        ;;
esac
