#!/bin/sh

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

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

doLog() {
## this is where the install and config takes place ##
echo "Formatting..."
if [ $RM_dataloc -eq 0 ] ; then
	flash_eraseall /dev/mtd/mtd3 > /dev/null
	[ $? -eq 0 ] || fail "Failed to format"
	mount -t yaffs2 /dev/block/mtdblock3 /data > /dev/null
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_dataloc -eq 1 ] ; then
	/bin/mke2fs -F /dev/block/mmcblk0p3 > /dev/null
	[ $? -eq 0 ] || fail "Failed to format"
	mount -t ext2 /dev/block/mmcblk0p3 /data
	[ $? -eq 0 ] || fail "Failed to mount"
elif [ $RM_dataloc -eq 2 ] ; 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"
	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
losetup /dev/block/loop2 /sdcard/andboot/databackup.img
[ $? -eq 0 ] || fail "Failed to mount"
mount -t ext2 /dev/block/loop2 /tmp
[ $? -eq 0 ] || fail "Failed to mount"
cp -a /tmp/* /data
[ $? -eq 0 ] || fail "Failed to copy"
cleanup
}
doLog 2>&1 | /bin/tee -a /bootlog.txt
