#! /bin/bash

set -ex

out=/output/grub-intel.raw

if [ -e $out ]; then
    rm $out
fi

# create the file
truncate -s 192M $out

# partition it
sgdisk \
    --new=1:2048:   --typecode=1:EF00 -c 1:boot   \
    --new=2:34:2047 --typecode=2:EF02 -c 2:BIOS-BOOT \
    --hybrid=1:2 --print $out

dev=$(losetup --find --show --partscan $out)
trap "losetup -d $dev" EXIT

# format filesystems
mkfs.vfat -n BLKBOOT ${dev}p1

# mount
mkdir -p /boot

mount ${dev}p1 /boot
trap "umount /boot" EXIT

mkdir -p /boot/grub
cp /assets/grub.cfg /boot/grub

devmap=/boot/grub/device.map
cat >$devmap <<EOF
(hd0) $dev
EOF

grub-install --target=i386-pc $dev
grub-install --target=x86_64-efi --removable --efi-directory=/boot

rm $devmap
