#!/bin/sh
# Add / update / remove the linux-ampere-fourier entries in
# /boot/firmware/extlinux/extlinux.conf, AND regenerate the initramfs.
# Idempotent. Coexists with the hand-managed labels in that file; never
# edits them. Default label is NOT touched — user picks at the u-boot menu.
#
# ampere boots from a vfat partition (mmcblk0p1) mounted at /boot/firmware/.
#
# TWO managed labels (NPU boot-fallback split, marfrit/kernel-agent #54/#55):
#   linux-ampere-fourier      base DTB, NPU nodes disabled -> rocket does NOT
#                             autoload. Safe default/fallback.
#   linux-ampere-fourier-npu  same + `fdtoverlays` applies the NPU overlay
#                             (.dtbo) -> 3 RKNN cores + /dev/accel come up.
# Boot the -npu label to use the NPU; boot the base label if it ever misbehaves.
# NOTE: the -npu label needs a U-Boot with `fdtoverlays` extlinux support;
# verify on first boot (worst case it silently boots NPU-off = still safe).

set -eu

CONF="/boot/firmware/extlinux/extlinux.conf"
TAG_BEGIN="# >>> linux-ampere-fourier (managed) >>>"
TAG_END="# <<< linux-ampere-fourier (managed) <<<"
IMG="/boot/firmware/Image-ampere-fourier"
DTB="/boot/firmware/rk3588-coolpi-cm5-genbook.dtb-ampere-fourier"
DTBO="/boot/firmware/rk3588-coolpi-cm5-genbook-npu.dtbo-ampere-fourier"

# --- initramfs regeneration -------------------------------------------------
# The stock mkinitcpio hook only fires on usr/lib/modules/*/vmlinuz, which
# this package does NOT create (the kernel lives at Image-ampere-fourier), so
# it never runs for us and the initramfs would go stale on every install.
# Regenerate here on install/upgrade. Non-fatal: a warning must not block the
# extlinux update.
if [ -f "$IMG" ] && command -v mkinitcpio >/dev/null 2>&1; then
  echo "linux-ampere-fourier: regenerating initramfs..."
  mkinitcpio -p linux-ampere-fourier || echo "linux-ampere-fourier: mkinitcpio reported warnings (check the initramfs)"
fi

# --- extlinux entries -------------------------------------------------------
# Source APPEND from a trusted existing label so the managed entries inherit
# the host's root=/console= settings: prefer the user's arch_mainline; else
# reuse our own prior managed entry (survives arch_mainline being removed);
# else a CoolPi GenBook default.
get_append() {
  awk -v want="$1" '
    $0 ~ "^[[:space:]]*label[[:space:]]+" want "[[:space:]]*$" { found=1; next }
    found && /^[[:space:]]*append[[:space:]]/ { sub(/^[[:space:]]*append[[:space:]]+/, ""); print; exit }
    /^[[:space:]]*label[[:space:]]/ { found=0 }
  ' "$CONF" 2>/dev/null || true
}
EXISTING_APPEND=$(get_append arch_mainline)
[ -z "$EXISTING_APPEND" ] && EXISTING_APPEND=$(get_append linux-ampere-fourier)
APPEND="${EXISTING_APPEND:-root=LABEL=arch rw rootwait rootfstype=btrfs rootflags=subvol=@,ssd,discard=async console=ttyS2,1500000 console=tty1 consoleblank=0 loglevel=7 cma=256M coherent_pool=2M}"

# Strip any prior managed block first
TMP=$(mktemp)
awk -v b="$TAG_BEGIN" -v e="$TAG_END" '
  $0==b{skip=1; next}
  $0==e{skip=0; next}
  !skip{print}
' "$CONF" > "$TMP"

# Post-Remove: kernel files absent -> don't re-add anything
if [ -f "$IMG" ] && [ -f "$DTB" ]; then
  {
    printf '%s\n' "$TAG_BEGIN"
    # base label: NPU OFF (safe default / fallback)
    printf 'label linux-ampere-fourier\n'
    printf '\tmenu label linux-ampere-fourier (managed, NPU off)\n'
    printf '\tkernel /Image-ampere-fourier\n'
    printf '\tinitrd /initramfs-ampere-fourier.img\n'
    printf '\tfdt    /rk3588-coolpi-cm5-genbook.dtb-ampere-fourier\n'
    printf '\tappend %s\n' "$APPEND"
    # NPU label: overlay applied (only if the .dtbo shipped)
    if [ -f "$DTBO" ]; then
      printf 'label linux-ampere-fourier-npu\n'
      printf '\tmenu label linux-ampere-fourier + NPU overlay (managed)\n'
      printf '\tkernel /Image-ampere-fourier\n'
      printf '\tinitrd /initramfs-ampere-fourier.img\n'
      printf '\tfdt    /rk3588-coolpi-cm5-genbook.dtb-ampere-fourier\n'
      printf '\tfdtoverlays /rk3588-coolpi-cm5-genbook-npu.dtbo-ampere-fourier\n'
      printf '\tappend %s\n' "$APPEND"
    fi
    printf '%s\n' "$TAG_END"
  } >> "$TMP"
  echo "linux-ampere-fourier: extlinux entries updated (base + NPU overlay)"
else
  echo "linux-ampere-fourier: kernel files absent, entries removed"
fi

mv "$TMP" "$CONF"
