#!/bin/sh
#  This file is part of sbctl.

COMMAND="$1"
KERNEL_VERSION="$2"
ENTRY_DIR_ABS="$3"
# shellcheck disable=SC2034  # Unused variables left for readability
KERNEL_IMAGE="$4"

IMAGE_FILE="$ENTRY_DIR_ABS/linux"

if [ "$KERNEL_INSTALL_LAYOUT" = "uki" ]; then
	UKI_DIR="$KERNEL_INSTALL_BOOT_ROOT/EFI/Linux"
	TRIES_FILE="${KERNEL_INSTALL_CONF_ROOT:-/etc/kernel}/tries"

	if [ -f "$TRIES_FILE" ]; then
		read -r TRIES <"$TRIES_FILE"
		if ! echo "$TRIES" | grep -q '^[0-9][0-9]*$'; then
			echo "$TRIES_FILE does not contain an integer." >&2
			exit 1
		fi
		IMAGE_FILE="$UKI_DIR/$KERNEL_INSTALL_ENTRY_TOKEN-$KERNEL_VERSION+$TRIES.efi"
	else
		IMAGE_FILE="$UKI_DIR/$KERNEL_INSTALL_ENTRY_TOKEN-$KERNEL_VERSION.efi"
	fi
fi

case "$COMMAND" in
add)
	printf 'sbctl: Signing kernel %s\n' "$IMAGE_FILE"

	# exit without error if keys don't exist
	# https://github.com/Foxboron/sbctl/issues/187
	if ! test -d /usr/share/secureboot/keys; then
		echo "Secureboot key directory doesn't exist, not signing!"
		exit 0
	fi

	sbctl sign -s "$IMAGE_FILE" 1>/dev/null
	;;
remove)
	if [[ -e "$IMAGE_FILE" ]]; then
	    [ "$KERNEL_INSTALL_VERBOSE" -gt 0 ] &&
		printf 'sbctl: Removing kernel %s from signing database\n' "$IMAGE_FILE"
	    sbctl remove-file "$IMAGE_FILE" 1>/dev/null
	fi
	;;
esac