#!/bin/sh -efu
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2021-2026 Anton Midyukov <antohami@altlinux.org>

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

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_PACK_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."

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

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

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

imgdir=/.image

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

if [ ! -f \$imgdir/boot/grub/bios.img ]; then
	printf '%s\\n' "$PROG: \$imgdir/boot/grub/bios.img: not found" >&2
	exit 1
fi

mkdir -p "\$imgdir"/.disk
cd "\$imgdir"/.disk
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

rc=0

cat > mkisofs << '_EOF_'
xorriso	-read_mkisofsrc \\
	-follow param \\
	$uuid_iso \\
	-as mkisofs \\
	$verbose -J -l -r -joliet-long \\
	-iso-level "${ISO_LEVEL:-2}" \\
	-exclude-list .exclude \\
	-eltorito-boot boot/grub/bios.img \\
	-no-emul-boot \\
	-boot-load-size 4 \\
	-boot-info-table \\
	-partition_offset 16 \\
	--eltorito-catalog boot/grub/boot.cat \\
	--grub2-boot-info \\
	--grub2-mbr ../boot/grub/i386-pc/boot_hybrid.img \\
	--mbr-force-bootable \\
	-eltorito-alt-boot \\
	-e EFI/.efiboot.img \\
	-no-emul-boot \\
	-append_partition 2 0xef ../EFI/.efiboot.img \\
	-appended_part_as_gpt \\
	../
_EOF_

eval "\$(cat mkisofs)" || rc=\$?

exit \$rc
EOF
