#!/bin/sh

PATH=/usr/sbin:/usr/bin:/sbin:/bin

IMAGE='/tmp/squashfs.img'
ROOTDEV=''
ROOTFS=''
INSTALLDEV=''
BOOTDEV='/dev/sda1'
MNTBOOT='/tmp/tmpboot'

GRUB_CONF=$MNTBOOT'/boot/grub/grub.conf'
TMP_GRUB_CONF=$MNTBOOT'grub.conf.back'

DEVICE=""

if [ -b /dev/hda ]; then
    DEVICE="/dev/hda"
elif [ -b /dev/sda ]; then
    DEVICE="/dev/sda"
elif [ -b /dev/vda ]; then
    DEVICE="/dev/vda"
fi

if [ "$DEVICE" == "" ]; then
    echo "There is no device selected, exit ..."
    exit -1
else
    echo "Found the device: "$DEVICE
fi

BOOTDEV=$DEVICE'1'

if [ ! -e "$IMAGE" ] ; then
    echo "There is no new image, exit ..."
    exit -1
fi

umount $BOOTDEV
mkdir $MNTBOOT
mount $BOOTDEV $MNTBOOT

function parse_opt() {
	case "$1" in
		*\=*)
		echo "$1" | cut -f2 -d=
		;;
	esac
}

# Get default root device and file system
if [ -r /rootdev ]; then
  ROOTDEV=`cat /rootdev`
fi
if [ -r /rootfs ]; then
  ROOTFS=`cat /rootfs`
fi

# Scan CMDLINE for any specified real_root etc.
CMDLINE=`cat /proc/cmdline`

echo $CMDLINE

for x in $CMDLINE
do
    case "$x" in
	    root\=*)
	    ROOTDEV=`parse_opt "$x"`
    esac
done

echo "rootdev = " $ROOTDEV

if [ "$ROOTDEV" == "$DEVICE""2" ]; then
    INSTALLDEV=$DEVICE"3"
elif [ "$ROOTDEV" == "$DEVICE""3" ]; then
    INSTALLDEV=$DEVICE"2"
else
    echo "There is no device where to install, exit ..."
    exit -1
fi

echo "===================================================="
echo "==================START INSTALATION================="
echo "===================================================="
echo "install dev = "$INSTALLDEV

umount $INSTALLDEV

echo "Clear the "$INSTALLDEV
mkfs.ext3 $INSTALLDEV

echo "Copy new file system to "$INSTALLDEV

dd if=$IMAGE of=$INSTALLDEV

if [ $? -eq 0 ]; then
    echo "The drive is ready, continue the installation ..."    
else
    echo "ERROR: cannot prepare new file system exit ..."
   exit -1
fi

echo "Now change the boot loader config file"

sed -e 's:'$ROOTDEV':'$INSTALLDEV':g' $GRUB_CONF > $TMP_GRUB_CONF

if [ $? -eq 0 ]; then
    cp -f $TMP_GRUB_CONF $GRUB_CONF
    
    if [ $? -eq 0 ]; then
	echo "grub.conf has changed" 
    else
	echo "ERROR: cannot create new grub.conf, exit ..."	
    exit -1
    fi

    rm -f $TMP_GRUB_CONF
    
else
    echo "ERROR: cannot create new grub.conf, exit ..."
   exit -1
fi

shutdown -r now