#! /bin/sh

STARTUP=/home/startup
EXTRACT=/home/.extract

# ensure that startup is executable and has a size greater than zero
# and .extract exists
if [ ! -x $STARTUP -o ! -s $STARTUP -o ! -e $EXTRACT ] ; then
	echo "(Re-)creating /home from @INSTALLER_FILE@"
	tar xzf @INSTALLER_FILE@ -C /home/
	echo "Syncing to disk..."
	sync
	touch $EXTRACT
	sync
	echo "/home is ready!"
fi

$STARTUP

# Application started
# TODO maybe check for success

# Update bootslot if necessary
if [ -s /home/bootslot ] ; then
	. /home/bootslot
fi

CMD_CURBOOTSLOT1="root=/dev/mtdblock4"
CMD_CURBOOTSLOT2="root=/dev/mtdblock5"

grep -q "$CMD_CURBOOTSLOT1" /proc/cmdline
RET=$?
if [ "$RET" -eq "0" ] ; then
    # current root is bootslot 1
    if [ "$bootslot" != "1" ] ; then
        echo "Mark bootslot 1 permanently active"
        echo "bootslot=1" > /home/bootslot.tmp
        sync
	mv -f /home/bootslot.tmp /home/bootslot
	sync
    fi
fi

grep -q "$CMD_CURBOOTSLOT2" /proc/cmdline
RET=$?
if [ "$RET" -eq "0" ] ; then
    # current root is bootslot 2
    if [ "$bootslot" != "2" ] ; then
        echo "Mark bootslot 2 permanently active"
        echo "bootslot=2" > /home/bootslot.tmp
        sync
	mv -f /home/bootslot.tmp /home/bootslot
	sync
    fi
fi

# ignore any other rootfs partition and type (e.g. SD card)

exit 0

