#!/bin/sh
# Add / update / remove the linux-fresnel-fourier entry in /boot/extlinux/extlinux.conf
# Idempotent. Coexists with the existing linux-eos-arm entry; never edits it.

set -eu

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

# What the entry should look like. APPEND copied from the existing
# linux-eos-arm entry where possible; otherwise sane PBP default.
EOS_APPEND=$(awk '/^[[:space:]]*APPEND/{print substr($0,index($0,"APPEND")+7); exit}' "$CONF" 2>/dev/null || true)
APPEND="${EOS_APPEND:-console=ttyS2,1500000 root=PARTLABEL=root rw rootwait}"

ENTRY=$(cat <<EOF
${TAG_BEGIN}
LABEL fresnel-fourier
        MENU LABEL fresnel-fourier OC kernel ($(uname -m))
        LINUX /Image-fresnel-fourier
        INITRD /initramfs-fresnel-fourier.img
        FDT /dtbs-fresnel-fourier/rockchip/rk3399-pinebook-pro.dtb
        APPEND ${APPEND}
${TAG_END}
EOF
)

# Strip any prior managed block first, 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"

# If the kernel files no longer exist (post-Remove), don't re-add the entry.
if [ -f "/boot/Image-fresnel-fourier" ] && [ -f "/boot/dtbs-fresnel-fourier/rockchip/rk3399-pinebook-pro.dtb" ]; then
  printf '%s\n' "$ENTRY" >> "$TMP"
  echo "linux-fresnel-fourier: extlinux entry updated"
else
  echo "linux-fresnel-fourier: kernel files absent, entry removed"
fi

mv "$TMP" "$CONF"
