#!/bin/sh

# If u want to use my stuff please drop my name somewhere
# dan1j3l
#

sleep 1
echo  "


###########################################################
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * #
#*                                                      * #
#*                        LeoFroyo                      * #
#*                     1.0 by dan1j3l                   * #
#*                                                      * #
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * #
###########################################################


"
sleep 3

mkdir -m 0755 /proc
mount -t proc proc /proc
mkdir -m 0755 /sys
mount -t sysfs sys /sys

#Configure Devices
MAKEDEVS

fail() {
    echo "Failed"
    echo "$1"
    exec /bin/sh
}
while [ ! -d /sys/block/mmcblk0 ] ; do
    echo "Waiting for SD Card"
    sleep 1
done
#Wait a bit once mmcblk0 appears
#Reading partition table could take some time
sleep 2

#Call it ... root= ?
#I don't do that because I don't want to interfer in any way with kernel
root_partition=`/bin/grep -o "root_partition=.*" /proc/cmdline | /bin/sed -e "s/.*root_partition=//g" -e "s/ .*//g"`
if ! [ "$root_partition" = "" ];then
	mkdir /rfs
	mount -t ext2 $root_partition /rfs
	exec switch_root /rfs /init
fi

partition=`/bin/grep -o "loop_partition=.*" /proc/cmdline | /bin/sed -e "s/.*loop_partition=//g" -e "s/ .*//g"`
if [ "$partition" = "" ];then
	partition="mmcblk0p1"
fi

# Try unpartitioned card
if [ ! -d /sys/block/mmcblk0/$partition ] ; then
    partition=mmcblk0
fi

mkdir -m 0777 /sdcard
echo "Running an fsck on the SD card"
dosfsck -y /dev/block/$partition
mount -t vfat -o fmask=0000,dmask=0000,utf8,rw,flush,noatime,nodiratime /dev/block/$partition /sdcard
[ $? -eq 0 ] || fail "Failed to mount the SD card. Cannot continue."

CARD_PATH=`/bin/grep -o "rel_path=.*" /proc/cmdline | /bin/sed -e "s/.*rel_path=//g" -e "s/ .*//g"`

if [ "$CARD_PATH" = "" ];then
	CARD_PATH="Android"
fi

if [ -d /sdcard/$CARD_PATH ] ; then
	card=/sdcard/$CARD_PATH
else
	card=/sdcard
fi

if [ -f $card/rootfs.img ] ; then
    root="$card/rootfs.img"
    SQUASHFS=0
elif [ -f $card/rootfs.sqsh ]; then
    root="$card/rootfs.sqsh"
    SQUASHFS=1
else
	fail "Failed to find rootfs on SD Card. You need to unzip a rootfs zip file to the root of your SD card."
fi

mkdir -m 0755 /rfs
losetup /dev/block/loop2 $root
[ $? -eq 0 ] || fail "Failed to mount rootfs on SD Card."

if [ $SQUASHFS -eq 0 ]; then
    e2fsck -y /dev/block/loop2
    mount -t ext2 -o noatime,nodiratime,sync,ro /dev/block/loop2 /rfs
    [ $? -eq 0 ] || fail "Failed to mount rootfs"
else
    mount -t squashfs -o noatime,nodiratime,sync,ro /dev/block/loop2 /rfs
    [ $? -eq 0 ] || fail "Failed to mount rootfs"
fi

#mkdir /rfs/dev
mount -t tmpfs -o size=100K tmpfs /rfs/dev
cp -a /dev/* /rfs/dev

echo "Cleaning up..."
umount -l /proc
umount -l /sys

echo "Switching to rootfs..."
exec switch_root /rfs /init
