#!/bin/sh
# /etc/initramfs/post-update.d/jd2-firmware-initramfs
#
# Closes the gap left by /etc/initramfs/post-update.d/z50-raspi-firmware,
# which rejects the -jd2 kernel suffix as "Unsupported initramfs version" and
# does not copy the regenerated initrd into /boot/firmware/.
#
# When update-initramfs regenerates /boot/initrd.img-$KVER for a -jd2 kernel,
# atomically copy it into the firmware partition under the CANDIDATE name.
# Tryboot promotion (candidate to active) is the jd2-tryboot-helper's job,
# not this hook's.

set -e

KVER="$1"
INITRD_PATH="$2"

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

if [ ! -r "${INITRD_PATH}" ]; then
    echo "jd2-firmware-initramfs: initrd not readable at ${INITRD_PATH}" >&2
    exit 0
fi

DST="/boot/firmware/initramfs_2712_jd2-candidate"
TMP="${DST}.tmp.$$"
install -m 0644 "${INITRD_PATH}" "${TMP}"
mv -f "${TMP}" "${DST}"
sync /boot/firmware/ 2>/dev/null || true

exit 0
