#!/bin/sh

export PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
UPDATE_TARBALL=update.tar.gz

echo "Update Script started"
pre_vers=`head -n 1 /etc/cabversion`

#####################################################################
## For AnyRover Mini / Emu4G
## JFFS2 maintenance work is suspected to cause unexpected system resets.
## This workaround tries to prevent that by
##  - ensuring the AnyRover reboots in ~10 minutes in case of failure
##  - Do the maintenance work before the update
##  - Pause JFFS2 maintenance during the update

reboot -d 920 &
pid=$!

gcd_pid="$(pidof jffs2_gcd_mtd3)"
if [ -n "${gcd_pid}" ]; then
	echo "Pausing JFFS2 garbage collector"
	kill -STOP ${gcd_pid}
else
	echo "JFFS2 garbage collector not running"
fi

echo "Syncing"
sync

##
#####################################################################

path=$PWD

echo "Updating RootFS"

rm -f /etc/dropbear/dropbear_ecdsa_host_key.pub
rm -f /etc/dropbear/dropbear_rsa_host_key.pub
rm -f /etc/init.d/S32gsmmuxer.sh
rm -f /usr/sbin/gsmMuxd
#<REMOVE>
cd /
tar xzf ${path}/${UPDATE_TARBALL}
sync

cd ${path}

## Finished, no more need for reboot, so cancel countdown
kill ${pid}

if [ -n "${gcd_pid}" ]; then
	echo "Resuming JFFS2 garbage collector"
	kill -CONT ${gcd_pid}
fi

echo "Update finished."

post_vers=`head -n 1 /etc/cabversion`
echo "Updated from ${pre_vers} to ${post_vers}"

echo "The config file /etc/cablynx.conf was untouched."
echo "Please use the new config file in /etc/cablynx.conf.${post_vers#*: }"

