#!/bin/sh
mount -t proc proc /proc

insmod /modules/usbcore.ko
insmod /modules/uhci-hcd.ko
insmod /modules/ehci-hcd.ko
insmod /modules/libusual.ko
insmod /modules/usb-storage.ko

if [ -n "$XANDROSBOOTDEBUG" ]; then
    /bin/busybox sh
    set -x
fi

ROOT=`cat /proc/cmdline | sed 's/.*root=// ; s/ .*//'`
USER=`cat /proc/cmdline | sed 's/.*user=// ; s/ .*//'`
#VERSION=`cat /proc/version | cut -f3 -d" "`
RPART=`echo $ROOT | sed 's/.*\///'`
UPART=`echo $USER | sed 's/.*\///'`

echo $RPART
echo $UPART

MAXWAIT=20
i=0;
#give up after 20 seconds.
while [[ $i -lt $MAXWAIT ]]; do
    if grep -q "$RPART" /proc/partitions ; then break; fi
    sleep 1
    i=$(( $i + 1 ))
done

while [[ $i -lt $MAXWAIT ]]; do
    if grep -q "$UPART" /proc/partitions ; then break; fi
    sleep 1
    i=$(( $i + 1 ))
done

mount -t ext2 -o ro $ROOT /mnt-system
if [ $? -ne 0 ] ; then
    echo Could not mount OS on $ROOT. Starting debugging shell....
    /bin/busybox sh
fi

if [ -n "$XANDROSSCAN" ]; then
    exec switch_root /mnt-system /sbin/scanuser.sh -- $USER
fi

if [ -n "$XANDROSRESTORE" ]; then
    exec switch_root /mnt-system /sbin/formatuser.sh -- $USER
fi

if [ -z "`grep nosplash /proc/cmdline`" ]; then
    echo -n "[?25l"
    cp /mnt-system/boot/startup.fb /dev/fb/0
fi

if ! mount -t ext3 -o rw $USER /mnt-user; then
    echo Error mounting user partition. Must run filesystem scan!
    exec switch_root /mnt-system /sbin/scanuser.sh -- $USER
fi 

# Factory auto-format functionality
if [ -f /mnt-user/.autoformat ]; then
    umount /mnt-user
    exec switch_root /mnt-system /sbin/formatuser.sh -- $USER --auto
fi

#insmod /mnt-system/lib/modules/$VERSION/kernel/fs/unionfs/unionfs.ko > /dev/null

mount -t unionfs -o dirs=/mnt-user=rw:/mnt-system=ro unionfs /mnt
if [ $? -ne 0 ]; then
    echo Could not mount unionfs. Starting debugging shell....
    /bin/busybox sh
fi

mount --move /mnt-system /mnt/mnt
umount -l /mnt-user

umount /proc

if [ -n "$INIT" ]; then
    if [ -n "$XANDROSBOOTDEBUG" ]; then
    exec switch_root /mnt $INIT </mnt/dev/console >/mnt/dev/console
    else
    exec switch_root /mnt $INIT </mnt/dev/null >/mnt/dev/null
    fi
else
    exec switch_root /mnt /sbin/fastinit "$@" </mnt/dev/console >/mnt/dev/console
fi

echo 
echo Init Failed. Starting emergency shell....
/bin/busybox sh
