#!/bin/sh -efu
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2019  Gleb Fotengauer-Malinovskiy <glebfm@altlinux.org>
# Copyright (C) 2020  Anton Midyukov <antohami@altlinux.org>

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

pkgs="${PACKAGES_REQUIRED_COPY_IEEE1275BOOT:-}"
imgdir="/.image${MKI_IMAGESUBDIR:+/$MKI_IMAGESUBDIR}"
grub_format="${GRUB_IEEE1275_FORMAT:-powerpc-ieee1275}"

verbose "has started executing."

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

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

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

. /.host/mki-chroot-sh-functions

GRUB_DIR=/usr/lib/grub/$grub_format
[ -d "\$GRUB_DIR" ] || GRUB_DIR=/usr/lib64/grub/$grub_format

cd "$imgdir"

mkdir $verbose -p boot/grub/$grub_format

grub-mkimage $verbose -O $grub_format -d "\$GRUB_DIR" \
	-p '()/boot/grub'  -o boot/grub/powerpc.elf \
	echo gzio iso9660 linux minicmd normal test

mkdir $verbose -p ppc

cp $verbose -af "\$GRUB_DIR"/bootinfo.txt -t ppc
cp $verbose -arf "\$GRUB_DIR" boot/grub
find boot/grub/"$grub_format" -type f -name '*.module' -delete ||:

kimage=
find_vmlinuz kimage

if [ -n "\$kimage" ]; then
	cp $verbose -af \$kimage boot/vmlinuz
	cp $verbose -af /boot/full.cz boot/full.cz
fi

[ ! -f 'EFI/BOOT/grub.cfg' ] || {
       echo >&2 'GRUB config EFI/BOOT/grub.cfg does not exist!'
       exit 1
}

exit 0
EOF
