#!/bin/bash -e

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

abi=$1
target=/boot/firmware

# A kernel is being removed. The firmware partition must keep reflecting the
# ACTIVE kernel, not merely the newest one -- so removing an unrelated old kernel
# (e.g. apt autoremove) must NOT silently switch which kernel the Pi boots.
# Prefer whatever /boot/Image points at (Armbian's active-kernel symlink); only
# if that kernel is gone (we just removed the active one) fall back to the newest
# kernel still installed. If none remain, clear the firmware.
want=""
img="$(readlink -f /boot/Image 2>/dev/null || true)"
if [[ -n "$img" && -f "$img" ]]; then
    v="$(basename "$img")"; v="${v#vmlinuz-}"
    [[ -d "/usr/lib/linux-image-$v" ]] && want="$v"
fi
if [[ -z "$want" ]]; then
    for k in /boot/vmlinuz-*; do
        [[ -e "$k" ]] || continue
        v="${k#/boot/vmlinuz-}"
        [[ "$v" == "$abi" ]] && continue
        [[ -d "/usr/lib/linux-image-$v" ]] || continue
        if [[ -z "$want" ]] || dpkg --compare-versions "$v" gt "$want"; then want="$v"; fi
    done
fi

if [[ -n "$want" ]]; then
    cp "/boot/vmlinuz-${want}" "${target}/vmlinuz"
    cp /usr/lib/linux-image-${want}/broadcom/*.dtb "${target}/"
    rm -rf "${target}/overlays.tmp"
    cp -rT /usr/lib/linux-image-${want}/overlays "${target}/overlays.tmp"
    rm -rf "${target}/overlays"
    mv "${target}/overlays.tmp" "${target}/overlays"
    sync -f "${target}/vmlinuz" || true
else
    rm -f "${target}/vmlinuz" "${target}"/*.dtb
    rm -rf "${target}/overlays"
fi

exit 0
