#!/bin/sh

fail() {
    echo "Failed"
    echo "$1"
    cleanup
}

cleanup() {
umount /system
if [ $RM_sysloc -eq 2 ] ; then
	losetup -d /dev/block/loop0
fi
umount /data
if [ $RM_dataloc -eq 2 ] ; then
	losetup -d /dev/block/loop1
fi
exec sleep 3
}

doLog() {
## this is where the install and config takes place ##
if [ $RM_sysloc -eq 0 ] ; then
	mount -t yaffs2 /dev/block/mtdblock2 /system > /dev/null
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_sysloc -eq 1 ] ; then
	mount -t ext2 /dev/block/mmcblk0p2 /system
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_sysloc -eq 2 ] ; then
	losetup /dev/block/loop0 /sdcard/andboot/system.img
	[ $? -eq 0 ] || fail "Failed to mount"
	mount -t ext2 /dev/block/loop0 /system
	[ $? -eq 0 ] || fail "Failed to mount"
fi

if [ $RM_dataloc -eq 0 ] ; then
	mount -t yaffs2 /dev/block/mtdblock3 /data > /dev/null
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_dataloc -eq 1 ] ; then
	mount -t ext2 /dev/block/mmcblk0p3 /data
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_dataloc -eq 2 ] ; then
	losetup /dev/block/loop1 /sdcard/andboot/data.img
	[ $? -eq 0 ] || fail "Failed to mount"
	mount -t ext2 /dev/block/loop1 /data
	[ $? -eq 0 ] || fail "Failed to mount"
fi

echo "Installing..."
if [ -f /sdcard/andboot/androidupdate.tgz ] ; then
	tar -xzf /sdcard/andboot/androidupdate.tgz -C /
else
	tar -xf /sdcard/andboot/androidupdate.tar -C /
fi
[ $? -eq 0 ] || fail "Failed to extract"
echo "Update complete!"
cleanup
}
doLog 2>&1 | /bin/tee -a /bootlog.txt
