#!/bin/bash


cdroot=cdroot
set -e
set -x
rm -rf $cdroot cd.iso

mkdir -p $cdroot/boot/grub
xxx=`mktemp`
{
    echo "search.fs_file /boot/grub/core.img root"
    echo 'set prefix=($root)/boot/grub'
} >| "$xxx"

grub-mkimage -c $xxx -O i386-pc biosdisk iso9660 search_fs_file > $cdroot/boot/grub/core.img

rm -f $xxx

krnl=/boot/vmlinuz-`uname -r`

cp $krnl                          $cdroot/boot/
cat /usr/lib/grub/i386-pc/cdboot.img \
    $cdroot/boot/grub/core.img  > $cdroot/boot/grub/stage2_eltorito
cp /usr/lib/grub/i386-pc/*.mod    $cdroot/boot/grub/
cp /usr/lib/grub/i386-pc/boot.img $cdroot/boot/grub/
cp /usr/lib/grub/i386-pc/*.lst    $cdroot/boot/grub/
cat > $cdroot/boot/grub/grub.cfg <<EOF
        menuentry 'test' --class os {
            linux $krnl
        }
EOF



#withous this, grub reports:
#grub-setup: warn: Attempting to install GRUB to a partitionless disk.  This is a BAD idea..
#grub-setup: warn: Embedding is not possible.  GRUB can only be installed in this setup by using blocklists.  However, blocklists are UNRELIABLE and their use is discouraged..
#grub-setup: error: cannot read `/grub/core.img' correctly.
mkdir -p $cdroot/grub
ln $cdroot/boot/grub/core.img $cdroot/grub/core.img

genisoimage -b boot/grub/stage2_eltorito -c boot/boot.cat -no-emul-boot \
    -boot-load-size 4 -boot-info-table -r -J -joliet-long -o cd.iso $cdroot

xxx=`mktemp`
echo "(iso) cd.iso" >| $xxx
grub-setup --force --skip-fs-probe -m $xxx -r "(iso)" -d $cdroot/boot/grub "(iso)"
rm -f $xxx
