#!/bin/sh
# SPDX-License-Identifier: 0BSD
# lpm-update-grub - run by the lpm hook /etc/lpm/hooks.d/grub-mkconfig.toml, with the
# root lpm works on as working directory, after a kernel in /boot changed.
#
# Regenerates /boot/grub/grub.cfg with grub-mkconfig, but only on the running system
# (not lpm --root) and only when grub-mkconfig wrote the current file.  A hand-written
# grub.cfg is left alone; then it only warns about kernels it boots that are gone.
cfg=boot/grub/grub.cfg
[ -f "$cfg" ] || exit 0
[ "$(stat -c %d:%i .)" = "$(stat -c %d:%i /)" ] || exit 0
if grep -q 'automatically generated by grub-mkconfig' "$cfg"; then
    exec grub-mkconfig -o /boot/grub/grub.cfg
fi
gone=0
for k in $(grep -o 'vmlinuz-[^[:space:]]*' "$cfg" | sort -u); do
    if [ ! -e "boot/$k" ]; then
        echo "warning: /boot/grub/grub.cfg (not written by grub-mkconfig) boots /boot/$k, which is gone" >&2
        gone=1
    fi
done
if [ $gone = 1 ]; then
    echo "  regenerate it: grub-mkconfig -o /boot/grub/grub.cfg (settings: /etc/default/grub)" >&2
fi
exit 0
