#!/bin/bash -e

# Play nice when run under debconf.
exec </dev/null >&2

abi=$1
target=/boot/firmware

# The kernel being installed ($abi) is the one that becomes active (its postinst
# relinks /boot/Image to it). Populate the firmware partition from it DIRECTLY --
# not from /boot/Image, which this hook (run via run-parts) sees before that
# relink and may still point at an older kernel when several are installed.
if [[ ! -f /boot/vmlinuz-${abi} ]]; then
    echo "Error: /boot/vmlinuz-${abi} not found; cannot update ${target}" >&2
    exit 1
fi
mkdir -p "${target}"
cp "/boot/vmlinuz-${abi}" "${target}/vmlinuz"
cp /usr/lib/linux-image-${abi}/broadcom/*.dtb "${target}/"
# refresh overlays atomically: stage a fresh copy, then swap, so a failed copy
# (set -e) aborts BEFORE the good overlays are removed, and cp -T avoids nesting.
rm -rf "${target}/overlays.tmp"
cp -rT /usr/lib/linux-image-${abi}/overlays "${target}/overlays.tmp"
rm -rf "${target}/overlays"
mv "${target}/overlays.tmp" "${target}/overlays"
sync -f "${target}/vmlinuz" || true

exit 0
