#!/bin/sh
# SPDX-License-Identifier: 0BSD
# lpm-mkinitcpio - run by the lpm hook /etc/lpm/hooks.d/60-mkinitcpio.toml, with the root
# lpm works on as working directory and the changed paths on stdin.
#
# boot/vmlinuz-<kver> that exists: build /boot/initramfs-<kver>.img; that is gone:
# delete the image.  Any other path (mkinitcpio, busybox, firmware, modules changed):
# rebuild the image of every installed kernel.  Only on the running system: for
# lpm --root, run mkinitcpio inside the new root (the installer and mkleiso do).
if [ "$(stat -c %d:%i .)" != "$(stat -c %d:%i /)" ]; then
    echo "  not the running system: run 'mkinitcpio -k <kver> -g /boot/initramfs-<kver>.img' in the new root" >&2
    exit 0
fi

build() {   # kver
    if [ ! -d "/usr/lib/modules/$1" ]; then
        echo "warning: no /usr/lib/modules/$1; no initramfs for $1" >&2
        return 0
    fi
    mkinitcpio -k "$1" -g "/boot/initramfs-$1.img" || status=1
}

status=0 all=0 kernels=
while IFS= read -r t; do
    case $t in
        boot/vmlinuz-*)
            k=${t#boot/vmlinuz-}
            if [ -e "/boot/vmlinuz-$k" ]; then
                kernels="$kernels $k"
            else
                rm -f "/boot/initramfs-$k.img"
                echo "  removed /boot/initramfs-$k.img"
            fi ;;
        *) all=1 ;;
    esac
done
if [ $all = 1 ]; then
    kernels=
    for v in /boot/vmlinuz-*; do
        [ -e "$v" ] && kernels="$kernels ${v#/boot/vmlinuz-}"
    done
fi
for k in $(printf '%s\n' $kernels | sort -u); do
    build "$k"
done
exit $status
