#!/bin/sh

if [ -f /etc/default/grub ]; then
	. /etc/default/grub
fi

if [ -z "$GRUB_CMDLINE_LINUX_DEFAULT" ]; then
	set -- $(cat /proc/cmdline)
	bootopts=
	for opt; do
		case "$opt" in
		initrd=*|BOOT_IMAGE=*|root=*|rootflags=*) ;;
		*) bootopts="$bootopts $opt";;
		esac
	done
	mkdir -p /etc/default
	echo "GRUB_CMDLINE_LINUX_DEFAULT=\"$bootopts\"" >> /etc/default/grub
fi

if [ -e /etc/grub-autoinstall ]; then
	. /etc/grub-autoinstall
elif [ "${1%-r*}" != "${2%-r*}" ]; then
	cat >&2 <<-EOF
	*
	* GRUB was upgraded. You may need to re-run grub-install before
	* rebooting. Put the command in /etc/grub-autoinstall to automate this.
	* If the firmware boots EFI/BOOT/BOOTX64.EFI, also run grub-install
	* with --removable.
	*
	EOF
fi

# warn about GRUB EFI loaders that do not match the installed modules
newver="${1%-r*}"
for f in /boot/EFI/*/*.efi /boot/efi/EFI/*/*.efi; do
	[ -f "$f" ] || continue
	v=$(grep -aoE 'grub-2\.[0-9]+(\.[0-9]+)?' "$f" 2>/dev/null | head -n1)
	[ -n "$v" ] || continue
	if [ "$v" != "grub-$newver" ]; then
		cat >&2 <<-EOF
		* WARNING: $f is $v, but modules are grub-$newver.
		*   It will fail to boot if the firmware uses it.
		*   Re-run grub-install for it (e.g. with --removable).
		EOF
	fi
done
