#!/bin/sh

# Install grub into a filesystem image
#
# Copyright (C) 2008 Zhigang Wang <w1z2g3@gmail.com>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>

imgfile=$1
dmname=joined
tmpfile=/tmp/tmp-$$.dsk
mapfile=/tmp/tmp-$$.map

# Device mapper can only operate on device file, using loop
dd if=/dev/zero of=$tmpfile bs=1M count=1
losetup /dev/loop0 $tmpfile
losetup /dev/loop1 $imgfile

# Clean up filesystem reserved metadata
# Note: PyGrub sometimes failed to open the image file if there are other
# metadata exist in the reserved space
dd if=/dev/zero of=/dev/loop1 bs=1K count=1
sync

# Create device mapper device
imgsize=`blockdev --getsize /dev/loop1`
echo -n "0 63 linear /dev/loop0 0
63 $imgsize linear /dev/loop1 0" | dmsetup create $dmname

# Wait for udev to create device node
sleep 1

# Create partition table
fdisk /dev/mapper/$dmname <<EOF
n
p
1


w
EOF

# Inform the OS of partition table changes
partprobe /dev/mapper/$dmname

# Generate device map
echo "(hd0) /dev/mapper/$dmname" >$mapfile

# Install grub
grub --device-map $mapfile <<EOF
root (hd0,0)
setup (hd0,0)
quit
EOF

# Clean up
dmsetup remove ${dmname}p1
dmsetup remove $dmname
losetup -d /dev/loop0
losetup -d /dev/loop1
rm -f $mapfile
rm -f $tmpfile

