#!/bin/sh

mkdir -p cdroot/boot

cat >early.cfg <<'EARLYCFG'
search.fs_label "Adelie-armv7" root
set prefix=($root)/boot
EARLYCFG

cat >cdroot/boot/grub.cfg <<'GRUBCFG'
menuentry "Adelie Linux Live (32-bit Arm)" --class linux --id adelie-live-cd-armv7 {
        insmod iso9660
        insmod linux
        search --label "Adelie-armv7" --no-floppy --set
        linux ($root)/kernel-armv7 root=live:LABEL=Adelie-armv7 rd.live.dir=/ rd.live.squashimg=armv7.squashfs softlevel=graphical
        initrd ($root)/initrd-armv7
}

menuentry "Adelie Linux Live (32-bit Arm) (text-only)" --class linux --id adelie-live-cd-armv7-text {
        insmod iso9660
        insmod linux
        search --label "Adelie-armv7" --no-floppy --set
        linux ($root)/kernel-armv7 root=live:LABEL=Adelie-armv7 rd.live.dir=/ rd.live.squashimg=armv7.squashfs
        initrd ($root)/initrd-armv7
}

menuentry "Reboot and Try Again" --class reboot --id reboot {
        reboot
}

GRUB_DEFAULT=adelie-live-cd
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR="Adelie"
GRUBCFG

if ! type grub-mkimage>/dev/null; then
	printf "GRUB image cannot be created.\n"
	exit 1
else
	printf '\033[01;32m * \033[37mInstalling GRUB...\033[00;39m\n'
	grub-mkimage -d target/usr/lib/grub/arm-efi -c early.cfg -p boot -o efi32.exe -O arm-efi boot btrfs datetime disk ext2 gfxmenu help iso9660 jfs ls luks lvm memdisk nilfs2 normal part_gpt part_msdos png scsi search xfs linux reboot gfxterm gfxterm_background gfxterm_menu all_video
fi

rm early.cfg

if ! type mkfs.fat>/dev/null || ! type mtools>/dev/null; then
	printf "EFI image creation tools cannot be located.\n"
	exit 1
fi

cat >mtoolsrc <<-MTOOLSRC
drive A: file="efi32.img"
MTOOLSRC
export MTOOLSRC="$PWD/mtoolsrc"
dd if=/dev/zero of=efi32.img bs=1024 count=1440
mkfs.fat efi32.img
mmd A:/EFI
mmd A:/EFI/BOOT
mcopy efi32.exe A:/EFI/BOOT/BOOTARM.EFI
rm efi32.exe mtoolsrc
