#!/bin/sh

# -----------------------------------------------------
# this script runs on the fox in the update folder to do the update
# -----------------------------------------------------

UPDATE_CONFIG=/var/local/data/update_type
RUN_FROM=/var/tmp
NEW_SHELL_FILE_NAME=new.sh
NEW_FILE_VERSION=/var/local/updates/clock_update_new_version
OLD_FILE_VERSION=/var/local/updates/clock_update_old_version
SD_NEW_FILE_VERSION=/var/sdcard/updates/clock_update_new_version
SD_OLD_FILE_VERSION=/var/sdcard/updates/clock_update_old_version
UPDATE_SHELL=/var/local/updates/clock_update.sh
CA_CERT=/usr/local/share/trustedcerts/cacerts.crt
#WGET_OPTIONS="-T 6 -t 2 --ca-certificate $CA_CERT"
WGET_OPTIONS="-T 30 -t 3 --ca-certificate $CA_CERT"

# ---------------------------------------------------------------------------------------
# Terminal colors
NORMAL='\033[0m'
GOOD='\033[32;01m'
WARN='\033[33;01m'
BAD='\033[31;01m'
BRACKET='\033[34;01m'

# ---------------------------------------------------------------------------------------
msg() {
	echo -e "${GOOD}Update: ${NORMAL} $*"
}

# ---------------------------------------------------------------------------------------
msg_error() {
	echo -e "${BAD}Update Error: ${NORMAL} $*"
	echo "[CSTC] updateclock Update Error: $*" > /dev/kmsg
}

# ---------------------------------------------------------------------------------------
# Toggle wdt pin (for portable/job clock. Not connected in normal clocks)
toggle_wdt() {
	WDT=94
	WDTP=C30
	echo $WDT > /sys/class/gpio/export
	echo out > /sys/class/gpio/pio$WDTP/direction
	echo 1 > /sys/class/gpio/pio$WDTP/value
	echo 0 > /sys/class/gpio/pio$WDTP/value
}

# ---------------------------------------------------------------------------------------

SCRIPT_NAME=`cat /proc/$$/status | sed -n 's/^Name://p' | cut -b 2-`
echo -e "${GOOD}================ $SCRIPT_NAME (`cat /proc/$$/cmdline`)================${NORMAL}"
PSCSAPI=$(ps -ef | grep csapi | wc -l)
if [ $PSCSAPI -lt 2 ]
then
	/usr/local/bin/csapi.sh 40 updateclock.script &
else 
	echo "csapi.sh already running"
fi
msg "Update: Running at: `date`"
#readlink /proc/$$/exe | grep $RUN_FROM
cat /proc/$$/cmdline | grep $RUN_FROM
if [ $? -ne 0 ]; then
	msg "Copying script from $0 to $RUN_FROM"
	mkdir -p $RUN_FROM
	cp -f $0 $RUN_FROM
	cd $RUN_FROM
	msg "About to run: $RUN_FROM/$SCRIPT_NAME $*"
	exec $RUN_FROM/$SCRIPT_NAME $*
	msg_error "Should never get here [1]"
fi

echo "-------------------------------------------------------------------------------------------------------"

# -----------------------------------------------------
# UPDATE_TYPE can be either: release, beta, or alpha
# -----------------------------------------------------
#if [ -s $UPDATE_CONFIG ]; then
#	. $UPDATE_CONFIG
#fi	
#UPDATE_TYPE=${UPDATE_TYPE-release}
UPDATE_TYPE_FILE="/var/local/data/update_type"
UPDATE_TYPE=$(cat $UPDATE_TYPE_FILE)

if [ "$1" = "--memstick" ]; then
	memstick=1
else 
	if [ "$2" = "--memstick" ]; then
		memstick=1
	else 
		memstick=0
	fi
fi

if [ "$1" = "--force" ]; then
	force=1
else 
	if [ "$2" = "--force" ]; then
		force=1
	else 
		force=0
	fi
fi

if [ "$1" = "--justforce" ]; then
	justforce=1
else 
	if [ "$2" = "--justforce" ]; then
		justforce=1
	else 
		justforce=0
	fi
fi

if [ "$justforce" -eq 1 ]; then
	msg "Just Force option selected. Deleting $OLD_FILE_VERSION"
	rm -f $OLD_FILE_VERSION
	exit 0
fi

if [ "$memstick" -eq 1 ]; then
	MEMSTICK_MOUNT_POINT=/mnt/1
	SECURE_FILE_VERSION=$MEMSTICK_MOUNT_POINT/$UPDATE_TYPE/new.txt
	SECURE_UPDATE=$MEMSTICK_MOUNT_POINT/$UPDATE_TYPE/$NEW_SHELL_FILE_NAME
else 
	SECURE_FILE_VERSION=https://www.capefox.com/secure/clocks3/$UPDATE_TYPE/new.txt
	SECURE_UPDATE=https://www.capefox.com/secure/clocks3/$UPDATE_TYPE/$NEW_SHELL_FILE_NAME
## TODO: check correct URI - replace above URIs
#	SECURE_FILE_VERSION=https://updates.cstimeclocks.com/secure/clocks3/$UPDATE_TYPE/new.txt
#	SECURE_UPDATE=https://updates.cstimeclocks.com/secure/clocks3/$UPDATE_TYPE/$NEW_SHELL_FILE_NAME
fi

# -----------------------------------------------------------------------------
# Startup
# -----------------------------------------------------------------------------
msg "Checking for Updates for this Clock"
msg "Update Type: $UPDATE_TYPE"

if [ "$force" -eq 1 ]; then
	msg "Force option selected. Deleting $OLD_FILE_VERSION"
	rm -f $OLD_FILE_VERSION
fi

toggle_wdt

# -----------------------------------------------------
# Step 1. Get new shell if it has been updated.
# -----------------------------------------------------
rm -f $NEW_FILE_VERSION
if [ "$memstick" -eq 1 ]; then
	/usr/local/bin/mount_usb
  result=`mount | grep $MEMSTICK_MOUNT_POINT`
  if [ -n "$result" ];
  then
	  msg "Downloading Update Version Information from the Memory Stick..."
  else
	  msg_error "Memory Stick not found"
    exit 28
  fi			
	cp -f $SECURE_FILE_VERSION $NEW_FILE_VERSION
else
	msg "Downloading Update Version Information from the Web..."
	msg "wget $WGET_OPTIONS -O $NEW_FILE_VERSION $SECURE_FILE_VERSION "
	wget $WGET_OPTIONS -O $NEW_FILE_VERSION $SECURE_FILE_VERSION 
fi 
if [ $? -ne 0 ]; then         # Test exit status of wget command.
	msg_error "Could not download update information from: $SECURE_FILE_VERSION"
	if [ "$memstick" -eq 1 ]; then
		umount $MEMSTICK_MOUNT_POINT > /dev/null 2>&1
	fi
	/usr/local/bin/csapi.sh 41 updateclock.script &
	exit 22
fi
chmod 0600 $NEW_FILE_VERSION

if [ ! -s $NEW_FILE_VERSION ] ; then
	msg_error "Update information file missing from: $NEW_FILE_VERSION"
	if [ "$memstick" -eq 1 ]; then
		umount $MEMSTICK_MOUNT_POINT > /dev/null 2>&1
	fi
		/usr/local/bin/csapi.sh 42 updateclock.script &
	exit 23
fi

if [ -s $OLD_FILE_VERSION ] ; then
	OLD_VERSION=`sed  -n '/(Build /s/.*(Build //p' $OLD_FILE_VERSION | sed 's/).*//'`
	NEW_VERSION=`sed  -n '/(Build /s/.*(Build //p' $NEW_FILE_VERSION | sed 's/).*//'`
	if [ $OLD_VERSION -lt $NEW_VERSION ]; then
		UPDATE_AVAILABLE=yes
	fi
else 
	UPDATE_AVAILABLE=yes
fi

if [ "$UPDATE_AVAILABLE" = "yes" ]; then         
	msg "A new update is available: `head -n 1 $NEW_FILE_VERSION`"
	rm -f $UPDATE_SHELL
	if [ "$memstick" -eq 1 ]; then
		msg "Downloading Update Script from the Memory Stick..."
		cp -f $SECURE_UPDATE $UPDATE_SHELL
	else
		msg "Downloading Update Script from the Web..."
		wget $WGET_OPTIONS -O $UPDATE_SHELL $SECURE_UPDATE
	fi 
	if [ $? -ne 0 ]; then         # Test exit status of wget command.
		msg_error "Could not download update information from: $SECURE_UPDATE"
		if [ "$memstick" -eq 1 ]; then
			umount $MEMSTICK_MOUNT_POINT > /dev/null 2>&1
		fi
		/usr/local/bin/csapi.sh 43 updateclock.script &
		exit 24
	fi
	if [ "$memstick" -eq 1 ]; then
		umount $MEMSTICK_MOUNT_POINT > /dev/null 2>&1
	fi
	chmod 0700 $UPDATE_SHELL
else
	if [ "$memstick" -eq 1 ]; then
		msg "Update: No new updates are available on the memory stick at: `date`"
	else
		msg "Update: No new web updates are available at: `date`"
	fi
	# exit with result code = 1 - this means that no updates were necessary
	exit 1
fi

# -----------------------------------------------------
# Step 2. If it exists, execute new.sh
# -----------------------------------------------------
if [ -s $UPDATE_SHELL ] ; then
	sha_a=`sha1sum $UPDATE_SHELL`
	sha_b=`sed -n "/$NEW_SHELL_FILE_NAME/s|$NEW_SHELL_FILE_NAME|$UPDATE_SHELL|p" $NEW_FILE_VERSION`
	msg "Download: $sha_a"
	msg "Orig    : $sha_b"
	if [ "$sha_a" != "$sha_b" ]; then
		msg_error "The downloaded file ($NEW_SHELL_FILE_NAME) does not match the Check Sum!! The downloaded files will be deleted. Please try again later."
		rm -f $UPDATE_SHELL
		rm -f $NEW_FILE_VERSION
		/usr/local/bin/csapi.sh 44 updateclock.script &
		exit 25
	fi 
	msg "Applying Update (either downloaded now or downloaded previously)..."
	chmod u+x $UPDATE_SHELL
	echo "-------------------------------------------------------------------------------------------------------"
	$UPDATE_SHELL $*
	if [ $? -ge 10 ]; then         # Test exit status of our update script command. >=10 = success, 1 = failure
## TODO: check for failure to switch servers
#		RETVAL=$?
		rm -f $UPDATE_SHELL
		cp -p $NEW_FILE_VERSION $OLD_FILE_VERSION
		# update /var/sdcard/updates
## TODO: switch server things
#		if [ $RETVAL -eq 11 ]; then
#			msg "Could not switch server. Will try again next time."
#		else
			cp -p $NEW_FILE_VERSION $SD_NEW_FILE_VERSION
			cp -p $OLD_FILE_VERSION $SD_OLD_FILE_VERSION
#		fi
		msg "Updating Successful - Rebooting Clock in 10 seconds..."
		sync
		sleep 10
		sync
## TODO: switch server things
#		if [ $RETVAL -eq 11 ]; then
#			/usr/local/bin/csapi.sh 47 updateclock.script &
#		else
			/usr/local/bin/csapi.sh 45 updateclock.script &
#		fi
		sleep 1
		msg "Updating Successful - Rebooting Clock now..."
		sleep 1
		#echo reboot clock now, remove debugging from updateclock
		/usr/local/bin/reboot.sh
	else 
		# rm -f $UPDATE_SHELL
		msg_error "Update Failed. Please try again later..."
		/usr/local/bin/csapi.sh 46 updateclock.script &
		# Start up the modem programs again (must be restarted before watchdog)
		sleep 4
		/etc/init.d/muxcontrol start
		wait
		/etc/init.d/pppcontrol start
		watchdog --quiet &
		exit 26
	fi 
fi

# -----------------------------------------------------
