#!/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
}

set_perm() {
	chown $1:$2 $4
	chmod $3 $4
}

set_perm_recursive() {
	chown -R $1:$2 $5
	chmod -R $3:$4 $5
}

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 "Fixing Permissions on files"
set_perm_recursive 0 0 0755 0644 /system
set_perm_recursive 0 0 0755 0644 /data/app_s
set_perm_recursive 0 2000 0755 0755 /system/bin
set_perm_recursive 0 2000 0755 0755 /system/xbin
set_perm 0 3003 02755 /system/bin/netcfg
set_perm 0 3004 02755 /system/bin/ping
set_perm 0 0 04755 /system/bin/pppd
set_perm_recursive 1002 1002 0755 0440 /system/etc/bluez
set_perm_recursive 0 2000 0755 0755 /system/etc/ppp
set_perm 0 0 0755 /system/etc/bluez
set_perm 1002 1002 0444 /system/etc/dbus.conf
set_perm 1014 2000 0550 /system/etc/dhcpcd/dhcpcd-run-hooks
set_perm 0 0 04755 /system/bin/su
set_perm 0 0 0700 /system/init
if [ -d /system/etc/wifi ]; then
	set_perm 0 0 0755 /system/etc/wifi/loadit
	set_perm 0 0 0755 /system/etc/wifi/wlan_loader
fi
set_perm_recursive 0 0 0755 0755 /system/etc/init.d

grep 995 /system/etc/apns-conf.xml > /dev/null
if [ $? -ne 0 ] ; then
	/bin/sed -i s.[:alnum:]*\<\/apns\>[:alnum:]*.. /system/etc/apns-conf.xml
	/bin/cat /bin/instscripts/cdmaapn >> /system/etc/apns-conf.xml
fi

# /bin/instscripts/fix_permissions

cleanup
}
doLog 2>&1 | /bin/tee -a /bootlog.txt
