#!/bin/bash

PATH=/usr/sbin:/usr/bin:/sbin:/bin

IMAGE='/mnt/bbram/bin/squashfs.img'
KERNEL_BIN='/mnt/bbram/bin/kernel.bin'
ROOTDEV=''
ROOTFS=''
INSTALLDEV=''
DEVICE=""

if [ ! -e "$IMAGE" ] ; then
    echo "There is no new image, exit ..."
    exit 1
fi

mkdir /tmp/testsquashfs
mount -o loop -t squashfs /mnt/bbram/bin/squashfs.img /tmp/testsquashfs
if [ $? -ne 0 ]; then
    echo "Invalid squashfs image ..."    
   exit 1
fi

umount /tmp/testsquashfs

parse_opt() {
	case "$1" in
		*\=*)
		echo "$1" | cut -f2 -d=
		;;
	esac
}

# Get default root device and file system
if [ -r /rootdev ]; then
  ROOTDEV=`cat /rootdev`
fi
if [ -r /rootfs ]; then
  ROOTFS=`cat /rootfs`
fi

# Scan CMDLINE for any specified real_root etc.
CMDLINE=`cat /proc/cmdline`

echo $CMDLINE

for x in $CMDLINE
do
    case "$x" in
	    root\=*)
	    ROOTDEV=`parse_opt "$x"`
    esac
done

if [ "$ROOTDEV" == "/dev/nande" ]; then
    INSTALLDEV="/dev/nandf"
elif [ "$ROOTDEV" == "/dev/nandf" ]; then
    INSTALLDEV="/dev/nande"
elif [ "$ROOTDEV" == "/dev/mmcblk0p8" ]; then
    INSTALLDEV="/dev/mmcblk0p9"
elif [ "$ROOTDEV" == "/dev/mmcblk0p9" ]; then
    INSTALLDEV="/dev/mmcblk0p8"
else
    echo "There is no device where to install, exit ..."
    exit 1
fi

echo "===================================================="
echo "==================START INSTALATION================="
echo "===================================================="
echo "install dev = "$INSTALLDEV

umount $INSTALLDEV

echo "Clear the "$INSTALLDEV
mkfs.ext4 $INSTALLDEV

echo "Copy new file system to "$INSTALLDEV

dd if=$IMAGE of=$INSTALLDEV

if [ $? -eq 0 ]; then
    echo "The drive is ready, continue the installation ..."    
    rm -f $IMAGE
else
    echo "ERROR: cannot prepare new file system exit ..."
   exit 1
fi

echo "Now change the environment variable for boot loader"
# get the current rootfs value from env
#
if [ "`envtool show bootcmd | grep nand`" != "" ]; then
	envtool show nand_root > /tmp/env_root
else
	envtool show mmc_root > /tmp/env_root
fi

if [ $? != 0 ]; then
    echo "Error while getting nand_root or mmc_root env val"
fi

sed -i 's:'$ROOTDEV':'$INSTALLDEV':g' /tmp/env_root
if [ $? != 0 ]; then
    echo "Error while replaceing nand_root val"
fi
ENV_ROOTFS_VAR=`cat /tmp/env_root`
echo $ENV_ROOTFS_VAR

# set then new value in env 
envtool $ENV_ROOTFS_VAR
if [ $? != 0 ]; then
    echo "Error while setting new nand_root env val"
fi

if [ -e "$KERNEL_BIN" ] ; then
    dd if=/dev/zero of=/dev/nandc bs=512
    dd if=$KERNEL_BIN of=/dev/nandc bs=512
fi

echo "Installation is complete, rebooting ..."

# Write all buffered blocks to disk
sync
sleep 20

# unmount all
umount -a

# reboot the device
reboot
