#!/bin/bash
#
# \brief   Create hard-disk image bootable via GRUB2
# \author  Christian Helmuth
# \date    2014-07-11
#
# We generate a head-image file only. This image contains MBR, label
# (partition table), and one primary partition where GRUB2 is installed. The
# image size fits only the GRUB2 binaries and must be extended later to include
# further binaries and data.
#
# Some parts of this script must be executed with superuser privileges and
# utilize 'sudo' for this purpose.

set -e
#set -x

#
# config
#

head_size="8MiB"
 head_img="grub2-head.img"

# generate image file
if [ -f $head_img ]; then
	echo "$head_img exists. Exiting..."
	exit 1
fi
fallocate -l $head_size $head_img

# prepare label and partition table
parted="parted -s $head_img -- unit MiB"

$parted "mklabel msdos"
$parted "mkpart primary ext2 1MiB -1s"

# loop image as disk (loop0) and partition 1 (loop1)
sudo losetup /dev/loop0 $head_img
sudo losetup /dev/loop1 $head_img -o 1MiB

# initialize ext2 on partition
sudo mkfs.ext2 /dev/loop1 -L GENODE -q -T default

# install GRUB2
mnt=$(mktemp -d)

sudo mount /dev/loop1 $mnt

sudo grub-install --root-directory=$mnt --no-floppy \
                  --modules="biosdisk part_msdos ext2" /dev/loop0

# generate GRUB2 configuration
cfg=$(mktemp)

cat > $cfg <<EOF
set prefix=(hd0,msdos1)/boot/grub

insmod normal
insmod legacycfg

terminal_input console
terminal_output console

## just legacy load Genode
legacy_configfile /boot/grub/menu.lst
EOF

sudo cp $cfg $mnt/boot/grub/grub.cfg

# cleanup
rm $cfg
sudo umount $mnt
rm -r $mnt
sudo losetup -d /dev/loop1
sudo losetup -d /dev/loop0
