#!/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=$!

echo "Syncing"
sync

gcd_pid="$(pidof jffs2_gcd_mtd3)"
if [ -n "${gcd_pid}" ]; then
	# proc_pid_stat(5):
	#   3: state (e.g. 'S' = Sleeping)
	#  14: utime (time in user mode)
	#  15: stime (time in system mode)
	#  if the value ($14+$15) does not increase, process is idle
	gcd_stat() { awk '{print $3, $14+$15}' /proc/${gcd_pid}/stat; }

	echo "Run JFFS2 garbage collector"
	# SIGHUP triggers the garbage collector to run now
	kill -HUP ${gcd_pid}

	# Wait until 5 consecutive idle samples
	idle=0
	prev=""
	while [ $idle -lt 5 ]; do
		# $1 = state, $2 = cpu ticks
		set -- $(gcd_stat)
		if [ "$1" = "S" ] && [ "$2" = "$prev" ]; then
			idle=$((idle + 1))
		else
			idle=0
		fi

		prev=$2

		sleep 1
	done

	echo "Pausing JFFS2 garbage collector"
	kill -STOP ${gcd_pid}
else
	echo "JFFS2 garbage collector not running"
fi
##
#####################################################################

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#*: }"

