#!/bin/bash

ARCH=amd64
TMPMOUNT=/tmp/xen
MIRROR=ftp://ftp.heanet.ie/mirrors/ubuntu

##############################################




if [ "$1" == "" ] ; then
        echo "No device/file given! Please supply a block device or file 1 GB at least in size, Exiting"
        exit 200;
fi


mkdir $TMPMOUNT


echo "Creating Filesystem"
if [ -f $1 ] ; then
        loopdev=`losetup -f`
        losetup  $loopdev $1
        mkfs.ext3 $loopdev &> /dev/null
        loopback=yes
        mount $loopdev $TMPMOUNT
elif [ -b $1 ] ; then
        if [ "`awk '{print $1}' /proc/mounts | grep $1 `" != "" ] ; then
                echo $1 is mounted. Exiting
                exit 200;
        fi
        mkfs.ext3 $1 &> /dev/null
        mount $1 $TMPMOUNT &> /dev/null
fi


##############################################

echo "Configuring base system"

debootstrap --arch=$ARCH --include=grub,linux-image-virtual --components=main,universe,multiverse intrepid $TMPMOUNT $MIRROR &> /dev/null
chroot $TMPMOUNT mv /etc/event.d/tty1 /etc/event.d/console
chroot $TMPMOUNT rm -f /etc/event.d/tty*
chroot $TMPMOUNT sed -ibak 's/tty1/console/g' /etc/event.d/console
echo "/dev/xvda1        /     ext3   defaults     1  1" >> $TMPMOUNT/etc/fstab
echo "/dev/xvda2        swap     swap   defaults     1  1" >> $TMPMOUNT/etc/fstab
echo  -e "auto lo\niface lo inet loopback" >> $TMPMOUNT/etc/network/interfaces
echo "ubuntu" > $TMPMOUNT/etc/hostname
chroot $TMPMOUNT dpkg --configure sysklogd &> /dev/null
chroot $TMPMOUNT dpkg-reconfigure klogd &> /dev/null
chroot $TMPMOUNT mkdir /boot/grub
chroot $TMPMOUNT update-grub -y &> /dev/null
chroot $TMPMOUNT dpkg --configure -a &> /dev/null
echo -e "password\npassword\n" |chroot $TMPMOUNT passwd &> /dev/null
fuser -k $TMPMOUNT &> /dev/null
umount $TMPMOUNT

##############################################

if [ "$loopback" == "yes" ] ; then
        losetup -d $loopdev
        echo "A sample Xen config file for this would be similar to this:"
        echo "memory = 512"
        echo "name = 'ubuntu'"
        echo "disk = ['file:$1,xvda1,w']"
        echo "bootloader='/usr/bin/pygrub'"
        echo "vif  = [ '' ]";
else
        echo "A sample Xen config file for this would be similar to this:"
        echo "memory = 512"
        echo "name = 'ubuntu'"
        echo "disk = ['phy:$1,xvda1,w']"
        echo "bootloader='/usr/bin/pygrub'"
        echo "vif  = [ '' ]";


fi



