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

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

if [[ $(getconf LONG_BIT) == 64 ]]; then
	: "${REFIND_ICON:=/usr/lib64/refind/refind/icons/os_${ID}.png}"
else
	: "${REFIND_ICON:=/usr/lib/refind/refind/icons/os_${ID}.png}"
fi

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

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

	if [[ ! -f ${REFIND_ICON} ]]; then
		die "REFIND_ICON=${REFIND_ICON} not found"
	fi

	einfo "Copying rEFInd icon file..."
	local icon="${img%.efi}.png"
	local icon_old=${icon%.png}.old.png
	if [[ ${INSTALLKERNEL_LAYOUT} == efistub ||
			${INSTALLKERNEL_LAYOUT} == uki ]]; then
		icon_old=${icon%.png}-old.png
	fi
	# If already installed, then move icon for the .old kernel
	if [[ -f ${icon} ]]; then
		mv "${icon}" "${icon_old}" || die
	fi
	install -m 0644 "${REFIND_ICON}" "${icon}" || die "Failed to copy icon file"

	# If there is a version-less image, install an icon for it
	local icon_nover=${icon//-${ver}/}
	local icon_nover_old=${icon_nover%.png}.old.png
	if [[ ${INSTALLKERNEL_LAYOUT} == efistub ||
			${INSTALLKERNEL_LAYOUT} == uki ]]; then
		icon_nover_old=${icon_nover%.png}-old.png
	fi

	if [[ -L ${icon_nover} ]]; then
		if [[ "$(readlink -f "${icon_nover}")" == "${icon}" ]]; then
			ln -sf "$(basename "${icon_old}")" "${icon_nover_old}" || die
		else
			mv "${icon_nover}" "${icon_nover_old}" || die
		fi
		ln -sf "$(basename "${icon}")" "${icon_nover}" || die
	elif [[ -f ${icon_nover} ]]; then
		mv "${icon_nover}" "${icon_nover_old}" || die
		install -m 0644 "${icon}" "${icon_nover}" || die
	elif [[ -L ${img//-${ver}/} ]]; then
		ln -sf "$(basename "${icon}")" "${icon_nover}" || die
	elif [[ -f ${img//-${ver}/} ]]; then
		install -m 0644 "${icon}" "${icon_nover}" || die
	fi
}

main
