#!/bin/sh -efu
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2007-2023  Alexey Gladkov <gladkov.alexey@gmail.com>
# Copyright (C) 2012  Michael Shigorin <mike@altlinux.org>

# shellcheck source=tools/mki-sh-functions
. "${0%/*}"/mki-sh-functions

verbose "has started executing."

# The EFI_BOOTLOADER had previously supported other values here.  Therefore,
# it's better to fail early if the profile specifies an EFI bootloader that is
# not supported.
case "${EFI_BOOTLOADER:-}" in
	''|grub-efi) ;;
	*) fatal "$EFI_BOOTLOADER EFI bootloader is not supported!" ;;
esac

pkgs="${PACKAGES_REQUIRED_COPY_GRUB_EFI:-}"

[ -d "$chroot" ] ||
	fatal "$dir: does not look like a hasher work directory."

[ -z "${EFI_CERT:-}" ] ||
	pkgs="$pkgs alt-uefi-certs shim-signed shim-unsigned"

mki-install $pkgs ||
	fatal "failed to install packages: $pkgs."

cp ${verbose-} -f -- "$bindir/mki-copy-grub-efi-chrooted" "$chroot/.host/grub-efi-chrooted"

make_exec "$chroot/.host/grub-efi.sh" <<EOF
#!/bin/sh -efu${verbose:+x}

verbose="$verbose"
EFI_CERT="${EFI_CERT-}"
EFI_FILES_COPY="${EFI_FILES_COPY-}"
EFI_FILES_REPLACE="${EFI_FILES_REPLACE-}"
UUID_ISO="${UUID_ISO:-}"

. /.host/grub-efi-chrooted
EOF

rc=0
mki-run "/.host/grub-efi.sh" || rc=$?
rm -f -- "$chroot/.host/grub-efi.sh"
find "$chroot/.in" -mindepth 1 -maxdepth 1 -exec rm -rf -- '{}' '+'
exit $rc
