#!/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>
# Copyright (C) 2019       Leonid Krivoshein <klark@altlinux.org>
# Copyright (C) 2019       Alexey Shabalin <shaba@altlinux.org>
# Copyright (C) 2020       Anton Midyukov <antohami@altlinux.org>

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

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_PACK_EFIONLY_ISOBOOT:-}"

outname="${MKI_OUTNAME:-outname}"
outname="${outname##*/}"

imgsubdir="${MKI_IMAGESUBDIR:-}"
imgsubdir="${imgsubdir#/}"

[ "$MKI_OUTNAME" = "${MKI_OUTNAME##*/}" ] ||
	outdir="$(readlink -ev "${MKI_OUTNAME%/*}")"

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

[ -f "$chroot/.image/$imgsubdir/EFI/.efiboot.img" ] ||
	fatal "/.image/$imgsubdir/EFI/.efiboot.img: not found."

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

run_chrooted "$chroot"  >"$outdir/$outname" <<EOF
#!/bin/sh -efu

imgdir=/.image
[ -z "$imgsubdir" ] || [ ! -d "/.image/$imgsubdir" ] ||
	imgdir="/.image/$imgsubdir"

cd /tmp
cat > .mkisofsrc <<-__EOF__
	APPI=${BOOT_APPI:-}
	COPY=${BOOT_COPY:-}
	ABST=${BOOT_ABST:-}
	BIBL=${BOOT_BIBL:-}
	PREP=${BOOT_PREP:-}
	PUBL=${BOOT_PUBL:-}
	SYSI=${BOOT_SYSI:-}
	VOLI=${BOOT_VOLI:-}
	VOLS=${BOOT_VOLS:-}
__EOF__

if [ -n "${MKI_EXCLUDE:-}" ]; then
	for d in ${MKI_EXCLUDE:-}; do
		printf '%s\\n' "\$d"
	done
fi > .exclude

uuid_iso=
if [ -n "${UUID_ISO:-}" ]; then
	uuid_iso="-volume_date uuid $(echo ${UUID_ISO:-} | sed 's/-//g')"
fi

rc=0
xorriso -follow param \
	-read_mkisofsrc \
	\$uuid_iso \
	-as mkisofs \
	$verbose -J -l -r -joliet-long \
	-c EFI/BOOT/boot.cat \
	-exclude-list /tmp/.exclude \
	-no-emul-boot \
	-boot-load-size 4 \
	-boot-info-table \
	-partition_offset 16 \
	--efi-boot EFI/.efiboot.img \
	-append_partition 2 0xef /.image/EFI/.efiboot.img \
	-appended_part_as_gpt \
	"\$imgdir/" || rc=\$?

rm -f -- .mkisofsrc .exclude
exit \$rc
EOF
