#!/bin/sh
# /etc/kernel/postinst.d/zz-jd2-firmware-sync
#
# Runs after /etc/kernel/postinst.d/z50-raspi-firmware (the zz- prefix orders
# us last alphabetically). z50 skips the -jd2 suffix harmlessly; this hook
# does the work for our kernel.
#
# - Copies the just-installed JD2 kernel image to
#   /boot/firmware/kernel_2712_jd2-candidate.img (atomic temp + rename).
# - Copies our DSI-bridge overlay (if present in this kernel's
#   /lib/linux-image-$KVER/overlays/) into /boot/firmware/overlays/.
# - Generates /boot/firmware/tryboot.txt from config.txt with kernel= pointed
#   at the candidate. On a tryboot reset the Pi 5 bootloader loads tryboot.txt
#   INSTEAD of config.txt, so the candidate trial config must live there; a
#   [tryboot] section in config.txt is never read during a tryboot.
#
# Tryboot promotion (candidate to active) is the jd2-tryboot-helper's job; it
# also removes tryboot.txt on commit/rollback.

set -e

KVER="$1"
VMLINUZ="$2"

case "${KVER}" in
    *-jd2|*-jd2.*) ;;   # old terminal "-jd2" AND new "-jd2.r<N>.g<hash>" KVER
    *) exit 0 ;;
esac

if [ ! -r "${VMLINUZ}" ]; then
    echo "zz-jd2-firmware-sync: vmlinuz not readable at ${VMLINUZ}" >&2
    exit 0
fi

DST_KERNEL="/boot/firmware/kernel_2712_jd2-candidate.img"
TMP_KERNEL="${DST_KERNEL}.tmp.$$"
install -D -m 0644 "${VMLINUZ}" "${TMP_KERNEL}"
mv -f "${TMP_KERNEL}" "${DST_KERNEL}"

SRC_OVERLAY="/usr/lib/linux-image-${KVER}/overlays/vc4-kms-dsi-ti-sn65dsi83-riverdi.dtbo"
if [ -r "${SRC_OVERLAY}" ]; then
    DST_OVERLAY="/boot/firmware/overlays/vc4-kms-dsi-ti-sn65dsi83-riverdi.dtbo"
    TMP_OVERLAY="${DST_OVERLAY}.tmp.$$"
    install -D -m 0644 "${SRC_OVERLAY}" "${TMP_OVERLAY}"
    mv -f "${TMP_OVERLAY}" "${DST_OVERLAY}"
fi

# Generate tryboot.txt: a copy of config.txt with the active kernel line
# rewritten to the candidate. The bootloader loads this (not config.txt) during
# a tryboot, so it must carry the full boot config (overlays, display, etc.) and
# differ only in which kernel it points at. Regenerated every stage so it tracks
# config.txt and can never drift.
CONFIG_TXT="/boot/firmware/config.txt"
TRYBOOT_TXT="/boot/firmware/tryboot.txt"
if [ -r "${CONFIG_TXT}" ]; then
    TMP_TRYBOOT="${TRYBOOT_TXT}.tmp.$$"
    sed 's#^kernel=/kernel_2712_jd2\.img$#kernel=/kernel_2712_jd2-candidate.img#' \
        "${CONFIG_TXT}" > "${TMP_TRYBOOT}"
    mv -f "${TMP_TRYBOOT}" "${TRYBOOT_TXT}"
else
    echo "zz-jd2-firmware-sync: ${CONFIG_TXT} not readable; skipped tryboot.txt" >&2
fi

sync /boot/firmware/ 2>/dev/null || true

exit 0
