#!/bin/sh

mount -o nosuid,strictatime,mode=755 -t devtmpfs devtmpfs /dev
mount -o nosuid,noexec,nodev -t sysfs sysfs /sys
mount -o nosuid,noexec,nodev -t proc proc /proc

/bin/mkdir /sysroot
/bin/mkdir /opt

#Find devices
ROOTFS=`/sbin/blkid -L rootfs`
if [ x$ROOTFS = "x" ]
then
    ROOTFS=`/sbin/blkid -t PARTLABEL=rootfs -o device`
fi
###Temporary Fix for SD card booting###
echo "Found Rootfs: " $ROOTFS
echo "Assigning to mmcblk1"
ROOTFS=/dev/mmcblk1p3
#######################################

MODULES=`/sbin/blkid -L modules`
if [ x$MODULES = "x" ]
then
    MODULES=`/sbin/blkid -t PARTLABEL=module -o device`
fi
###Temporary Fix for SD card booting###
echo "Found Modules: " $MODULES
echo "Assigning to mmcblk1"
MODULES=/dev/mmcblk1p2
#######################################

DATAFS=`/sbin/blkid -L system-data`
if [ x$DATAFS = "x" ]
then
    DATAFS=`/sbin/blkid -t PARTLABEL=system-data -o device`
fi
###Temporary Fix for SD card booting###
echo "Found Datafs: " $DATAFS
echo "Assigning to mmcblk1"
DATAFS=/dev/mmcblk1p5
#######################################

#Check and mount devices
FIRSTBOOT=1
if [ x"$DATAFS" != "x" ]
then
    /bin/mount $DATAFS /opt

    if [ -e /opt/var/.fsck_done ]
    then
        FIRSTBOOT=0
    else
        echo " " > /opt/var/.fsck_done
        /bin/umount /opt
    fi
fi

if [ x$ROOTFS != "x" ]
then
    if [ "$FIRSTBOOT" = "1" ]
    then
        /sbin/resize2fs -f $ROOTFS
        /sbin/fsck -y $ROOTFS
    fi
    /bin/mount $ROOTFS /sysroot
else
    echo "WARNING : THERE IS NO ROOTFS."
    exec /bin/sh
fi

if [ x"$DATAFS" != "x" ]
then
    if [ "$FIRSTBOOT" = "1" ]
    then
        /sbin/resize2fs -f $DATAFS
        /sbin/fsck -y $DATAFS
        /bin/mount $DATAFS /sysroot/opt
    else
        /bin/mount -M /opt /sysroot/opt
    fi
fi

if [ -e /sysroot/opt/sqsh_usr.img ]
then
    if [ ! -d /sysroot/usr ]
    then
        /bin/mkdir /sysroot/usr
    fi
    echo "Mounting Squash FS to /usr..."
    /bin/mount /sysroot/opt/sqsh_usr.img /sysroot/usr
fi

if [ x$MODULES != "x" ]
then
    if [ "$FIRSTBOOT" = "1" ]
    then
        /sbin/resize2fs -f $MODULES
        /sbin/fsck -y $MODULES
    fi
    /bin/mount $MODULES /sysroot/usr/lib/modules
fi


cd /sysroot
mkdir -p ./initrd

/sbin/pivot_root . ./initrd
/bin/mount -M ./initrd/dev /dev
/bin/mount -M ./initrd/sys /sys
/bin/mount -M ./initrd/proc /proc
/bin/umount -l ./initrd
/bin/rm -r ./initrd

INIT=/sbin/init

if [ $$ = 1 ]
then
  exec chroot . $INIT $@
  #/bin/chroot . $INIT $@
fi
exec /bin/sh
