#!/bin/sh
# Add / update / remove the linux-ampere-fourier entry in
# /boot/firmware/extlinux/extlinux.conf. Idempotent. Coexists with
# the hand-managed labels in that file; never edits them. Default
# label is NOT touched — user picks at u-boot menu.
#
# ampere boots from a vfat partition (mmcblk0p1) mounted at
# /boot/firmware/, distinct from fresnel's /boot/ on root.

set -eu

CONF="/boot/firmware/extlinux/extlinux.conf"
TAG_BEGIN="# >>> linux-ampere-fourier (managed) >>>"
TAG_END="# <<< linux-ampere-fourier (managed) <<<"

# Copy APPEND from the user's `arch_mainline` label so the managed
# entry inherits the same root= and console= settings the host's
# bootloader already trusts. Falls back to a CoolPi GenBook default
# if no arch_mainline label exists (first-time install on a fresh
# bootloader config).
EXISTING_APPEND=$(awk '
  /^[[:space:]]*label[[:space:]]+arch_mainline[[:space:]]*$/ { found=1; next }
  found && /^[[:space:]]*append[[:space:]]/ {
    sub(/^[[:space:]]*append[[:space:]]+/, "")
    print
    exit
  }
  /^[[:space:]]*label[[:space:]]/ { found=0 }
' "$CONF" 2>/dev/null || true)

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}"

ENTRY=$(cat <<EOF
${TAG_BEGIN}
label linux-ampere-fourier
	menu label linux-ampere-fourier (managed)
	kernel /Image-ampere-fourier
	initrd /initramfs-ampere-fourier.img
	fdt    /rk3588-coolpi-cm5-genbook.dtb-ampere-fourier
	append ${APPEND}
${TAG_END}
EOF
)

# Strip any prior managed block, then append fresh
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 the entry
if [ -f "/boot/firmware/Image-ampere-fourier" ] \
   && [ -f "/boot/firmware/rk3588-coolpi-cm5-genbook.dtb-ampere-fourier" ]; then
  printf '%s\n' "$ENTRY" >> "$TMP"
  echo "linux-ampere-fourier: extlinux entry updated"
else
  echo "linux-ampere-fourier: kernel files absent, entry removed"
fi

mv "$TMP" "$CONF"
