#!/usr/bin/env bash

# Copyright 2020-2024 Gentoo Authors
# This script is installed by sys-kernel/installkernel, it is executed by the
# traditional installkernel, NOT by systemd's kernel-install. I.e. this plugin
# is run when the systemd USE flag is disabled or SYSTEMD_KERNEL_INSTALL=0 is
# set in the environment.

: "${GRUB_CFG:=/boot/grub/grub.cfg}"

# familiar helpers, we intentionally don't use Gentoo functions.sh
die() {
	echo -e " ${NOCOLOR-\e[1;31m*\e[0m }${*}" >&2
	exit 1
}

einfo() {
	[[ ${INSTALLKERNEL_VERBOSE} == 1 ]] || return 0
	echo -e " ${NOCOLOR-\e[1;32m*\e[0m }${*}"
}

ewarn() {
	echo -e " ${NOCOLOR-\e[1;33m*\e[0m }${*}"
}

eerror() {
	echo -e " ${NOCOLOR-\e[1;31m*\e[0m }${*}" >&2
}

main() {
	# re-define for subst to work
	[[ -n ${NOCOLOR+yes} ]] && NOCOLOR=

	# do nothing if somehow GRUB is not installed
	[[ -x $(command -v grub-mkconfig) ]] || { ewarn "grub-mkconfig command not available" && exit 0; }

	if [[ -f ${GRUB_CFG} ]]; then
		einfo "Backing up existing grub config as ${GRUB_CFG}~..."
		cp --dereference --preserve=all "${GRUB_CFG}"{,~} || die "Failed to save existing config"
	fi

	if [[ -f /etc/os-release ]]; then
		# shellcheck source=/dev/null
		. /etc/os-release
	elif [[ -f /usr/lib/os-release ]]; then
		# shellcheck source=/dev/null
		. /usr/lib/os-release
	fi

	# Set sane default if no or broken os-release
	: "${NAME:=Linux}"

	# The default GRUB_LINUX_KERNEL_GLOBS from /etc/grub/10_linux expanded
	# with efistub dir
	: "${GRUB_LINUX_KERNEL_GLOBS:="
		/boot/vmlinuz-* /boot/vmlinux-* /boot/kernel-* /vmlinuz-* /vmlinux-* /kernel-*
		/boot/EFI/EFI/${NAME}/vmlinuz-*.efi /boot/EFI/EFI/${NAME}/vmlinux-*.efi
		/boot/EFI/EFI/${NAME}/kernel-*.efi /boot/efi/EFI/${NAME}/vmlinuz-*.efi
		/boot/efi/EFI/${NAME}/vmlinux-*.efi /boot/efi/EFI/${NAME}/kernel-*.efi
		/boot/EFI/${NAME}/vmlinuz-*.efi /boot/EFI/${NAME}/vmlinux-*.efi
		/boot/EFI/${NAME}/kernel-*.efi /efi/EFI/${NAME}/vmlinuz-*.efi
		/efi/EFI/${NAME}/vmlinux-*.efi /efi/EFI/${NAME}/kernel-*.efi
	"}"
	export GRUB_LINUX_KERNEL_GLOBS

	einfo "Generating new GRUB config as ${GRUB_CFG}..."
	local dname="${GRUB_CFG%/*}"
	mkdir -vp "${dname}" || die "Failed to mkdir ${dname}"
	# Exit non-fatally to ensure emerge does not fail completely in containers
	grub-mkconfig -o "${GRUB_CFG}" || eerror "grub-mkconfig failed"
}

main
