#!/bin/bash

msg () {
    echo "$@" >&2
}


if [ $# -ne 3 ]; then
    echo "Usage: $0 <imgfile> <size> <distrib>" >&2
    echo "  <imgfile>: name of file to create" >&2
    echo "  <size>: size in gigabytes" >&2
    echo "  BUILDIMG_NOGRUB: skip grub install" >&2	
    echo "  LOOPFILE: choose an alternate loopback file" >&2	
    echo >&2
    echo "!!! This script is dangerous, be careful !!!" >&2
    exit 1
fi

IMGFILE="$1"
IMGRAWSIZE="$2"
LOOPFILE=${LOOPFILE:-/dev/loop0}

heads=255
sectors=63
cylinders=`expr \( $IMGRAWSIZE \* 1024 \* 1024 \* 1024 \) \/ \( 512 \* $heads \* $sectors \) \+ 1`
realsize=`expr \( $cylinders \* $sectors \* $heads \* 512 \) \/ 1024`

#Do some sanity check on specified device
if [ -e "$IMGFILE" ]; then
    echo "Image file already exists, aborting." >&2
    exit 1
fi
if grep "$IMGFILE" /proc/mounts >/dev/null 2>/dev/null; then
	echo "Specified device found in /proc/mounts, aborting." >&2
    exit 1
fi

if losetup $LOOPFILE >/dev/null 2>/dev/null; then
	echo "Loop '$LOOPFILE' already used, aborting." >&2
    exit 1
fi

qemu-img create -f raw "${IMGFILE}" $realsize
if [ $? -ne 0 ]; then
    echo "Error while creating image, aborting." >&2
    exit 1
fi

msg "Partitionning..."
sfdisk -D $IMGFILE <<EOF
,,L,*
;
;
;
EOF
if [ $? -ne 0 ]; then
    echo "Error while partitionning, aborting." >&2
    exit 1
fi


msg "Formating..."

# 32256 is 63*512 ; it's because -D is used for sfdisk, there is some stuffing.
losetup -o 32256 $LOOPFILE "${IMGFILE}"

mkfs.ext3 "${LOOPFILE}"

INSTDIR=/tmp/buildimage
mkdir -p $INSTDIR

msg "Getting local grub files..."
mount -n ${LOOPFILE} $INSTDIR

rmdir $INSTDIR/lost+found

# Get grub files from local disk to avoid grub versions mismatches
mkdir -p $INSTDIR/local/grub
GRUBDIR=/boot/grub
cp $GRUBDIR/{stage1,stage2,e2fs_stage1_5} $INSTDIR/local/grub
ln -s /boot/grub/menu.lst $INSTDIR/local/grub/menu.lst

umount -n $INSTDIR

losetup -d $LOOPFILE

if [ -z $BUILDIMG_NOGRUB ]; then
    msg "Installing bootloader..."
grub --batch <<EOF
device (hd0) ${IMGFILE}
root (hd0,0)
setup --prefix=/local/grub (hd0)
quit
EOF

else
    msg "Skipping bootloader..."
fi



