#! /bin/sh
#
#  Copyright (C) 2010 Hemisphere GPS, Inc.
#


MOUNT_POINT=/mnt/usbdisk

# update redboot image

echo "Writing redboot partition"
#nandwrite -p pads raw binary with empty oob data
if [ -f $MOUNT_POINT/redboot.bin ]; then
    flash_eraseall /dev/mtd0
    nandwrite -p /dev/mtd0 /mnt/usbdisk/redboot.bin
fi

echo "Checking which rootfs is mounted"
cat /proc/cmdline | grep mtdblock3
if [ $? = 0 ];
then
    echo "Upgrading mtd5"
    FIS_CONFIG_FILE=fis_config_5.bin
    ROOTFS_DEVICE=/dev/mtd5
else
    echo "Upgrading mtd3"
    FIS_CONFIG_FILE=fis_config_3.bin
    ROOTFS_DEVICE=/dev/mtd3
fi


echo "Writing kernel partition"
# kernel upgrade
if [ -f $MOUNT_POINT/zImage ]; then
    flash_eraseall /dev/mtd2
    nandwrite -p /dev/mtd2 /mnt/usbdisk/zImage
fi

echo "Writing kernel2 partition"
# kernel 2 (upgrade) update
if [ -f $MOUNT_POINT/zImage ]; then
    flash_eraseall /dev/mtd4
    nandwrite -p /dev/mtd4 /mnt/usbdisk/zImage
fi


# Now comes rootfs upgrade.

# first, upgrade rootfs2 - pass -j to erase helps out jffs2 driver on mounting -> sets up erase sector info.
echo "Writing root partition"
if [ -f $MOUNT_POINT/rootfs.jffs2 ]; then
    flash_eraseall -j $ROOTFS_DEVICE
    nandwrite -p $ROOTFS_DEVICE /mnt/usbdisk/rootfs.jffs2
fi

echo "Writing fis config/dir partition"
# update redboot config and fis directory "-o" to nandwrite tells it file contains oob data
if [ -f $MOUNT_POINT/$FIS_CONFIG_FILE ]; then
    flash_eraseall /dev/mtd1
    nandwrite -o /dev/mtd1 /mnt/usbdisk/$FIS_CONFIG_FILE
fi

echo "syncing file systems"
# sync three tiimes purely for paranoia
sync
sync
sync

echo "rebooting..."
# we are done, so reboot into our lovely newly upgraded system (cross fingers).
sleep 10

reboot

