#!/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.
#
# - Stages the just-installed JD2 kernel and its exact initramfs as one matched
#   candidate pair using jd2-tryboot-stage.
# - 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

INITRD="/boot/initrd.img-${KVER}"
/usr/sbin/jd2-tryboot-stage "${KVER}" "${VMLINUZ}" "${INITRD}"

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

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

exit 0
