#!/usr/bin/env bash

# Copyright 2023-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 }${*}"
}

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

	if [[ -n "${INSTALLKERNEL_INITRD_GENERATOR}" &&
		${INSTALLKERNEL_INITRD_GENERATOR} != dracut ]]; then
			# We are not selected as the initrd generator
			einfo "initrd_generator=${INSTALLKERNEL_INITRD_GENERATOR}, skipping dracut"
			exit 0
	fi

	# do nothing if somehow dracut is not installed
	[[ -x $(command -v dracut) ]] || { ewarn "dracut is not installed, not generating an initramfs" && exit 0; }

	# Skip kernel installation if zfs has not been built yet
	if (grep ' / ' /proc/mounts | grep -q zfs) && ! modinfo zfs -k "${ver}" &>/dev/null
	then
		[[ ${INSTALLKERNEL_VERBOSE} == 1 ]] && ewarn \
			"root is zfs, but the zfs module is missing, please build the zfs module and retry"
		exit 77
	fi

	initramfs_gen_args=(
		# if uefi=yes is used, dracut needs to locate the kernel image
		--kernel-image "${img}"
		--force
	)

	[[ ${INSTALLKERNEL_VERBOSE} == 1 ]] && initramfs_gen_args+=( --verbose )

	if [[ ${INSTALLKERNEL_INITRD_GENERATOR} == dracut ]]; then
		if [[ ${INSTALLKERNEL_UKI_GENERATOR} == dracut ]]; then
			einfo "Using dracut as the initramfs and UKI generator..."
			initramfs_gen_args+=( --uefi )
			out=uki.efi
		else
			einfo "Using dracut as the initramfs generator..."
			initramfs_gen_args+=( --no-uefi )
			out=initrd
		fi
	else
		einfo "initrd_generator=${INSTALLKERNEL_INITRD_GENERATOR}, not running dracut"
		exit 0
	fi

	initramfs_gen_args+=(
		# positional arguments
		"${INSTALLKERNEL_STAGING_AREA}/${out}" "${ver}"
	)

	dracut "${initramfs_gen_args[@]}" || die "Failed to generate initramfs"
}

main
