#!/usr/bin/env bash
#shellcheck disable=SC2034,SC2140

# Copyright 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.

ver=${1}
img=${2}

# 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=

	local install_dir=/boot
	local kernel=
	local initrd=
	if [[ ${INSTALLKERNEL_LAYOUT} == "uki" ]]; then
		for candidate in /boot/EFI /boot/efi /boot /efi; do
			if [[ -d ${candidate}/EFI/Linux ]]; then
				install_dir=${candidate}
			else
				continue
			fi
		done
		kernel=${install_dir}/EFI/Linux/${ID}-${ver}.efi
		initrd=
	elif [[ ${INSTALLKERNEL_LAYOUT} == "efistub" ]]; then
		for candidate in /boot/EFI /boot/efi /boot /efi; do
			if [[ -d ${candidate}/EFI/${NAME} ]]; then
				install_dir=${candidate}
			else
				continue
			fi
		done
		kernel=${install_dir}/EFI/${NAME}/vmlinuz-${ver}.efi
		initrd=${install_dir}/EFI/${NAME}/initramfs-${ver}.img
	elif [[ ${INSTALLKERNEL_LAYOUT} == "compat" || ${INSTALLKERNEL_LAYOUT} == "grub" ]]; then
		kernel=${install_dir}/vmlinuz-${ver}
		initrd=${install_dir}/initramfs-${ver}.img
	else
		ewarn "WARNING: unknown layout, log will be incomplete"
		KERNEL=unknown
		INITRD=
	fi
	[[ ! -f ${initrd} ]] && initrd=unknown
	[[ ! -f ${kernel} ]] && kernel=unknown

	INSTALLKERNEL_PLUGINS="${INSTALLKERNEL_PREINST_PLUGINS:+${INSTALLKERNEL_PREINST_PLUGINS} }${INSTALLKERNEL_POSTINST_PLUGINS}"

	if [[ -z ${INSTALLKERNEL_CONF_ROOT} ]]; then
		if [[ -f /etc/kernel/install.conf ]]; then
			INSTALLKERNEL_CONF_ROOT=/etc/kernel
		elif [[ -f /usr/lib/kernel/install.conf ]]; then
			INSTALLKERNEL_CONF_ROOT=/usr/lib/kernel
		fi
	fi

	local state=/var/lib/misc/installkernel
	local log=/var/log/installkernel.log

	einfo "Appending installed kernel to ${log}..."


	#shellcheck disable=SC2155
	local logline=\
"$(LC_ALL=C date)\t"\
"gentoo\t"\
"${ver:-notset}\t"\
"${INSTALLKERNEL_CONF_ROOT:-notset}\t"\
"${INSTALLKERNEL_LAYOUT:-notset}\t"\
"${INSTALLKERNEL_INITRD_GENERATOR:-notset}\t"\
"${INSTALLKERNEL_UKI_GENERATOR:-notset}\t"\
"${install_dir:-notset}\t"\
"${kernel#"${install_dir}/"}\t"\
"${initrd#"${install_dir}/"}\t"\
"${INSTALLKERNEL_PLUGINS:-notset}"

	echo -e "${logline}" > "${state}" || exit 1
	echo -e "${logline}" >> "${log}" || exit 1
}

main
