#!/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
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"

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

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


SCRIPT_NAME=`cat /proc/$$/status | sed -n 's/^Name://p' | cut -b 2-`
echo -e "${GOOD}================ $SCRIPT_NAME (`cat /proc/$$/cmdline`)================${NORMAL}"
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}

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/clocks/$UPDATE_TYPE/new.txt
	SECURE_UPDATE=https://www.capefox.com/secure/clocks/$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

# -----------------------------------------------------
# Step 1. Get new shell if it has been updated.
# -----------------------------------------------------
rm -f $NEW_FILE_VERSION
if [ "$memstick" -eq 1 ]; then
  #largeflash=`mount | grep /mnt/3 | grep sda1`
  #if [ -n "$largeflash" ];
  #then
  #  mount	-t vfat -o umask=0000 /dev/sdb1 $MEMSTICK_MOUNT_POINT 
  #else
  #  mount -t vfat -o umask=0000 /dev/sda1 $MEMSTICK_MOUNT_POINT  
  #fi
	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 27
  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
	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
	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
		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
		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. 0 = success, 1 = failure
		rm -f $UPDATE_SHELL
		cp -p $NEW_FILE_VERSION $OLD_FILE_VERSION
		msg "Updating Successful - Rebooting Clock in 10 seconds..."
		sync
		sleep 10
		sync
		usleep 50
		msg "Updating Successful - Rebooting Clock now..."
		usleep 50
		#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..."
		watchdog --quiet &
		exit 26
	fi 
fi

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

