#!/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}}"
target="/dev/mmcblk0"
image_url="${LAB_RPI4_OS_IMAGE_URL:-https://downloads.raspberrypi.com/raspios_lite_arm64_latest}"
cache_dir="${LAB_RPI4_IMAGE_CACHE_DIR:-${HOME}/.cache/homelab/rpi4}"
static_ip="${LAB_RPI_HOST:-${LAB_RASPBERRY_HOST:-192.168.100.89}}"
gateway="${LAB_RPI4_GATEWAY:-192.168.100.1}"
dns_servers="${LAB_RPI4_DNS_SERVERS:-192.168.100.73 1.1.1.1}"
public_key="${LAB_RPI4_SSH_PUBLIC_KEY:-}"

if [[ -z "${public_key}" && -r "${HOME}/.ssh/id_ed25519.pub" ]]; then
    public_key="$(<"${HOME}/.ssh/id_ed25519.pub")"
fi

case "${action}" in
    plan)
        cat <<EOF
RPi4 image installation plan
============================
image: Raspberry Pi OS Lite (64-bit)
source: ${image_url}
target: ${target}
Pi: ${rpi_user}@${rpi_host}

Precondition: the Pi must be booted from the Debian NFS staging root.
The active SD card is never written while it is mounted as /.
EOF
        ;;
    apply)
        [[ "${2:-}" == "--yes" ]] || { echo "Use: scripts/rpi4-image-install apply --yes" >&2; exit 2; }
        [[ -n "${public_key}" ]] || { echo "An SSH public key is required" >&2; exit 2; }
        root_source="$(ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "${rpi_user}@${rpi_host}" 'findmnt -no SOURCE /')"
        if [[ "${root_source}" != /dev/nfs* && "${root_source}" != *:* ]]; then
            if [[ ! -t 0 ]]; then
                echo "Remote EEPROM modification requires an interactive confirmation terminal." >&2
                exit 2
            fi
            printf 'This will change %s EEPROM BOOT_ORDER from SD-first to network-first and reboot it. Type CHANGE-RPI4-BOOT to continue: ' "${rpi_host}" >&2
            read -r confirmation
            [[ "${confirmation}" == "CHANGE-RPI4-BOOT" ]] || { echo "Confirmation did not match; aborting." >&2; exit 2; }
            ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" 'cat >/tmp/jeannie-eeprom-editor <<"EDITOR"
#!/bin/sh
sed -i "s/^BOOT_ORDER=.*/BOOT_ORDER=0xf2/" "$1"
EDITOR
chmod 0755 /tmp/jeannie-eeprom-editor
sudo env EDITOR=/tmp/jeannie-eeprom-editor VISUAL=/tmp/jeannie-eeprom-editor rpi-eeprom-config --edit
rm -f /tmp/jeannie-eeprom-editor
sudo reboot' || true
            echo "Waiting for the Pi to return on its Debian NFS root..."
            for _ in $(seq 1 90); do
                sleep 2
                root_source="$(ssh -i "${rpi_key}" -o BatchMode=yes -o ConnectTimeout=3 "${rpi_user}@${rpi_host}" 'findmnt -no SOURCE /' 2>/dev/null || true)"
                if [[ "${root_source}" == /dev/nfs* || "${root_source}" == *:* ]]; then
                    break
                fi
            done
        fi
        [[ "${root_source}" == /dev/nfs* || "${root_source}" == *:* ]] || { echo "Refusing image: Pi root is ${root_source}, not NFS" >&2; exit 2; }
        mkdir -p "${cache_dir}"
        image_file="${cache_dir}/raspios_lite_arm64_latest.img.xz"
        curl -fL --retry 3 "${image_url}" -o "${image_file}"
        xz -t "${image_file}"
        echo "Writing Raspberry Pi OS image (XZ integrity checked) to ${target}..."
        xz -dc "${image_file}" | ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" "sudo dd of=${target} bs=16M conv=fsync status=progress"
        ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" 'sudo partprobe /dev/mmcblk0; for i in $(seq 1 30); do test -b /dev/mmcblk0p1 && test -b /dev/mmcblk0p2 && exit 0; sleep 1; done; exit 1'
        password_hash="$(openssl passwd -6 "$(openssl rand -hex 24)")"
        key_b64="$(printf '%s' "${public_key}" | base64 | tr -d '\n')"
        dns_csv="${dns_servers// /,}"
        ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" bash -s -- "${password_hash}" "${key_b64}" "${static_ip}" "${gateway}" "${dns_csv}" <<'REMOTE'
set -euo pipefail
password_hash="$1"; key_b64="$2"; static_ip="$3"; gateway="$4"; dns_csv="$5"
boot=$(mktemp -d); root=$(mktemp -d)
cleanup() { sudo umount "$boot" "$root" 2>/dev/null || true; rmdir "$boot" "$root" 2>/dev/null || true; }
trap cleanup EXIT
sudo mount /dev/mmcblk0p1 "$boot"
sudo mount /dev/mmcblk0p2 "$root"
sudo touch "$boot/ssh"
printf 'jv:%s\n' "$password_hash" | sudo tee "$boot/userconf.txt" >/dev/null
sudo mkdir -p "$root/home/jv/.ssh" "$root/etc/NetworkManager/system-connections"
printf '%s\n' "$(printf '%s' "$key_b64" | base64 -d)" | sudo tee "$root/home/jv/.ssh/authorized_keys" >/dev/null
sudo chmod 0700 "$root/home/jv/.ssh"; sudo chmod 0600 "$root/home/jv/.ssh/authorized_keys"
sudo tee "$root/etc/NetworkManager/system-connections/eth0.nmconnection" >/dev/null <<NET
[connection]
id=eth0
type=ethernet
interface-name=eth0
[ipv4]
method=manual
addresses=${static_ip}/24
gateway=${gateway}
dns=${dns_csv}
[ipv6]
method=disabled
NET
sudo chmod 0600 "$root/etc/NetworkManager/system-connections/eth0.nmconnection"
printf 'rpi4\n' | sudo tee "$root/etc/hostname" >/dev/null
sudo sed -i 's/^127\.0\.1\.1.*/127.0.1.1\trpi4/' "$root/etc/hosts" || true
sudo mkdir -p "$root/etc/sudoers.d"
printf 'jv ALL=(ALL) NOPASSWD:ALL\n' | sudo tee "$root/etc/sudoers.d/90-homelab-jv" >/dev/null
sudo chmod 0440 "$root/etc/sudoers.d/90-homelab-jv"
REMOTE
        ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" 'sudo raspi-config nonint do_boot_order B3 || true'
        echo "RPi4 image installed and headless configuration injected. Rebooting..."
        ssh -i "${rpi_key}" -o BatchMode=yes "${rpi_user}@${rpi_host}" 'sudo reboot' || true
        ;;
    *)
        echo "Usage: scripts/rpi4-image-install {plan|apply --yes}" >&2
        exit 2
        ;;
esac
