#!/usr/bin/env sh

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

COMMAND="${1}"
KERNEL_IMAGE="${4}"

if [ "${COMMAND}" != "add" ]; then
	exit 0
fi

IMAGE_DIR=$(dirname "${KERNEL_IMAGE}")
INITRD=${IMAGE_DIR}/initrd
UKI=${IMAGE_DIR}/uki.efi

if [ -f "${INITRD}" ]; then
	[ "${KERNEL_INSTALL_VERBOSE}" = "1" ] && echo "Copying prebuilt initramfs to staging area"
	cp --dereference --preserve=all "${INITRD}" "${KERNEL_INSTALL_STAGING_AREA}/initrd" || exit 1
fi

if [ -f "${UKI}" ]; then
	[ "${KERNEL_INSTALL_VERBOSE}" = "1" ] && echo "Copying prebuilt UKI to staging area"
	cp --dereference --preserve=all "${UKI}" "${KERNEL_INSTALL_STAGING_AREA}/uki.efi" || exit 1
fi

if [ -f "/boot/intel-uc.img" ]; then
	[ "${KERNEL_INSTALL_VERBOSE}" = "1" ] && echo "Copying prebuilt Intel early microcode image to staging area"
	cp --dereference --preserve=all "/boot/intel-uc.img" "${KERNEL_INSTALL_STAGING_AREA}/microcode-intel" || exit 1
fi

if [ -f "/boot/amd-uc.img" ]; then
	[ "${KERNEL_INSTALL_VERBOSE}" = "1" ] && echo "Copying prebuilt AMD early microcode image to staging area"
	cp --dereference --preserve=all "/boot/amd-uc.img" "${KERNEL_INSTALL_STAGING_AREA}/microcode-amd" || exit 1
fi
