#!/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 ##
echo "Formatting..."
if [ $RM_sysloc -eq 0 ] ; then
	flash_eraseall /dev/mtd/mtd2 > /dev/null
	[ $? -eq 0 ] || fail "Failed to format"
	mount -t yaffs2 /dev/block/mtdblock2 /system > /dev/null
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_sysloc -eq 1 ] ; then
	/bin/mke2fs -F /dev/block/mmcblk0p2 > /dev/null
	[ $? -eq 0 ] || fail "Failed to format"
	mount -t ext2 /dev/block/mmcblk0p2 /system
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_sysloc -eq 2 ] ; then
	if [ -f /sdcard/andboot/system.img ] ; then
		rm -Rf /sdcard/andboot/system.img
	fi
	dd if=/dev/zero of=/sdcard/andboot/system.img bs=1048576 count=256
	[ $? -eq 0 ] || fail "Failed to format"
	/bin/mke2fs -F /sdcard/andboot/system.img
	[ $? -eq 0 ] || fail "Failed to format"
	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
	if [ $RM_wipedataforsys = "yes" ] ; then
		flash_eraseall /dev/mtd/mtd3 > /dev/null
		[ $? -eq 0 ] || fail "Failed to format"
	fi
	mount -t yaffs2 /dev/block/mtdblock3 /data > /dev/null
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_dataloc -eq 1 ] ; then
	if [ $RM_wipedataforsys = "yes" ] ; then
		/bin/mke2fs -F /dev/block/mmcblk0p3 > /dev/null
		[ $? -eq 0 ] || fail "Failed to format"
	fi
	mount -t ext2 /dev/block/mmcblk0p3 /data
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_dataloc -eq 2 ] ; then
	if [ $RM_wipedataforsys = "yes" ] ; then
		if [ -f /sdcard/andboot/data.img ] ; then
			rm -Rf /sdcard/andboot/data.img
		fi
		dd if=/dev/zero of=/sdcard/andboot/data.img bs=1048576 count=256
		[ $? -eq 0 ] || fail "Failed to format"
		/bin/mke2fs -F /sdcard/andboot/data.img
		[ $? -eq 0 ] || fail "Failed to format"
	fi
	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 [ -d /data/dalvik-cache ] ; then
	/bin/rm -Rf /data/dalvik-cache
fi
if [ -d /data/app_s ] ; then
	/bin/rm -Rf /data/app_s
fi

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