#!/bin/sh
#  Note:	The above line determines what interpreter to use to interpret this script.
######################################################
#
#  Program Name:		upgraderadar24
#
#  Program Description:	This script upgrades the Radar 24 software.
#
#  Return value:
#	0				- installation successful
#	<error code>		- one of the exit codes defined below (100-127)
#
#  NOTE:	THIS SCRIPT ASSUMES THAT THE "disk_id" AND THE "chunk" FILES EXIST IN THE
#		CURRENT WORKING DIRECTORY.
#
#  Rights to this program:
#
#  This script file is the property of iZ technology corporation (www.iZcorp.com).
#  Unauthorized distribution and/or use of this script is strictly prohibited and subject
#  to applicable laws.
#
######################################################

#
#  Common constants, variables and functions
#

source ${0%/*}/installfunctions

#
#  Declare local constants and variables.
#
#  NOTE: 	To handle file names with spaces in them, the name and variable need to be
#		"surrounded by double quotes" like in this sentence.

MYNAME=${0##*/}
INSTALL_LOG="${INSTALL_LOGS_DIR}/${MYNAME}.log"
LOG_RESULTS="/bin/tee -a ${INSTALL_LOG}"

NETWORK_FILE="${HOME_DIR}/config/settings/network"
NETWORK_FILE_VALID="${HOME_DIR}/config/settings/network.radar"
NET_SWITCH_DIR="${HOME_DIR}/net_switch"
BONE_INSTALL_HOME="${HOME_DIR}/bone_install"
RADAR_RESET="${INSTALL_DIR}/RadarReset2"

# Error Code Constants.
# NOTE: 'ret' is a global constant, containing the script's final return code
#
EXIT_CODE_BONE_INSTALLED=100
EXIT_CODE_UNABLE_TO_REQUEST_REBOOT=114
EXIT_CODE_UNABLE_TO_CAT_CHUNKS=115
EXIT_CODE_INSTALL_CORRUPT=116
EXIT_CODE_UNABLE_TO_GET_UPGRADE_INFO=117

declare -a installfile		# Install files.
declare -a checksum		# Install file checksums.


##########################################################
#  Function definition section.
##########################################################

function Initialize
{
	# Initialize install log
	/bin/rm -f $INSTALL_LOG
	/bin/touch $INSTALL_LOG
	LogMessage "${MYNAME}:\n"
}

function CleanUp
{
	#  Make a copy of the install log file and add a timestamp to the file name
	/bin/cp $INSTALL_LOG ${INSTALL_LOG}.`/bin/date '+%c'|tr -s ' ' '-'`

	#  Report where the details of this particular installation instance can be found
	PrintMessage "\nSee $INSTALL_LOG for the results of this script.\n"
}

function GetUpgradeInfo
{
	LogMessage "Getting Upgrade Information ... "

	if [ ! -f "${INSTALL_DIR}/$DISK_ID_FILE" ]
	then
		LogMessage "ERROR: Can't find file '${INSTALL_DIR}/$DISK_ID_FILE'--upgrade info not available."
		ret=$EXIT_CODE_UNABLE_TO_GET_UPGRADE_INFO
		return $ret
	fi

	s_disknum=$(/bin/head -1 ${INSTALL_DIR}/$DISK_ID_FILE | awk '{print $1}')
	s_disklast=$(/bin/head -1 ${INSTALL_DIR}/$DISK_ID_FILE | awk '{print $3}')
	i_disknum=$((s_disknum))
	i_disklast=$((s_disklast))

	BUILD_FILE_NAME=$(/bin/grep "Build file:" ${INSTALL_DIR}/$DISK_ID_FILE | /bin/awk '{print $3}')
	local temp=${BUILD_FILE_NAME##*-}
	BUILD_FILE_VER=${temp%%.zip}
	if [ "$BUILD_FILE_VER" = "" ]
	then
		BUILD_FILE_VER="0.00"
	fi

	s_cksum_current=$(/bin/tail -1 ${INSTALL_DIR}/$DISK_ID_FILE | awk '{print $1}')
	local installinfoblock=$(/bin/grep "Install entry" ${INSTALL_DIR}/$DISK_ID_FILE | /bin/awk -F: '{print $2":"$3}')
	declare -i entry_count=$(/bin/grep -c "Install entry" ${INSTALL_DIR}/$DISK_ID_FILE)
	declare -i j=0

	for entry in $installinfoblock
	do
		installfile[$j]="$INSTALL_DIR/${entry%%:*}"
		checksum[$j]=${entry##*:}
		#LogMessage "$entry"
		#LogMessage "${installfile[$j]}\t${checksum[$j]}"
		j=$j+1
	done
	#LogMessage "$entry_count entries found."

	return $EXIT_CODE_OK
}

function InstallSoftware
{
	LogMessage "Concatenating chunk files ... "

	if /bin/cat ${INSTALL_DIR}/$CHUNK_FILE_PREFIX* > ${INSTALL_DIR}/$BUILD_FILE_NAME
	then
		LogMessage "Verifying proper installation ... "

		s_cksum_build=$(/bin/cksum ${INSTALL_DIR}/$BUILD_FILE_NAME | /bin/awk '{ print $1$2 }')
		if [ "$s_cksum_current" = "$s_cksum_build" ]
		then
			LogMessage "Unzipping installation zip file '${INSTALL_DIR}/$BUILD_FILE_NAME' to '$HOME_DIR' ... "

			if /bin/unzip -o ${INSTALL_DIR}/$BUILD_FILE_NAME -d $HOME_DIR
			then
				# All is well
				ret=$EXIT_CODE_OK
			else
				LogMessage "ERROR: Unable to unzip RADAR software package."
				ret=$EXIT_CODE_UNABLE_TO_UNZIP
			fi
		else
			LogMessage "ERROR: RADAR 24 software package is corrupt."
			LogMessage "(Disk checksum = $s_cksum_current, Build checksum = $s_cksum_build)"
			ret=$EXIT_CODE_INSTALL_CORRUPT
		fi
	else
		LogMessage "ERROR: Unable to build RADAR 24 software package."
		ret=$EXIT_CODE_UNABLE_TO_CAT_CHUNKS
	fi

	if [ "$ret" = "EXIT_CODE_OK" ]
	then
		# Check that a valid network setting file exists
		if [ -s "${NETWORK_FILE}" ]
		then
			LogMessage "Current network settings are valid."
		else
			/bin/cp -f ${NETWORK_FILE_VALID} ${NETWORK_FILE}
			local ret_cp=$?
			if [ "$ret_cp" != "0" ]
			then
				LogMessage "ERROR: Current network settings are invalid, but couldn't replace with valid file."
			else
				LogMessage "Current network settings are invalid--replace with valid file."
			fi
		fi
	fi

	return $ret
}

function CheckInstalledFiles
{
	local cs
	declare -i j=0

	for file in ${installfile[@]}
	do
		if [ -f "$file" ]
		then		
			LogMessage "\nChecking ${installfile[$j]} integrity ..."
			cs=$(/bin/cksum "${installfile[$j]}" | /bin/awk '{ print $1$2 }')
			#LogMessage "$cs\tinstalled file checksum\n${checksum[$j]}\toriginal file checksum"
			if [ "$cs" != "${checksum[$j]}" ]
			then
				LogMessage "ERROR: One or more of the installed files are corrupt."
				LogMessage "('${installfile[$j]}': Disk checksum = ${checksum[$j]}, Build checksum = $cs)"
				ret=$EXIT_CODE_INSTALL_CORRUPT
				return $ret
			fi

			LogMessage "Integrity OK."
			j=$j+1
		fi
	done
	LogMessage "\nIntegrity maintained for all installed files.\n"

	return $EXIT_CODE_OK
}

function InstallComplete
{
	# Install BONE networking if required
	if [ -f "${NET_SWITCH_DIR}/netserver_d/Netscript" ]
	then
		LogMessage "BONE has already been installed!"
	else
		LogMessage "BONE has not been installed!"

		if [ -f "${BONE_INSTALL_HOME}/do_bone_install" ]
		then		
			${BONE_INSTALL_HOME}/do_bone_install
			LogMessage "\nBONE networking full install successful."

			# Mark the first install of BONE
			touch ${NET_SWITCH_DIR}/bone_d/firstinstall
			ret=$EXIT_CODE_BONE_INSTALLED
			return $ret
		fi
	fi

	return $EXIT_CODE_OK
}

function RequestReboot
{
	if [ ! -f "$RADAR_RESET" ]
	then
		LogMessage "Unable to run Reboot Notification app because '$RADAR_RESET' not found."
		# This is not a global error
		return $EXIT_CODE_UNABLE_TO_REQUEST_REBOOT
	fi

	LogMessage "Running '$RADAR_RESET' to request a reboot ... "

	# Clean up and sync filesystem now, since we won't be exiting normally
	CleanUp
	/bin/sync

#	$RADAR_RESET "Remove CD/floppy" "and reboot RADAR" 0
	$RADAR_RESET "Remove CD/floppy" "ENTER to reboot "

	# Remove the Radar reset program we just ran so that it does not run again
	# until next time it is installed (then sync filesystem again)
	PrintMessage "Removing '$RADAR_RESET' ... "
	/bin/rm -f $RADAR_RESET
	/bin/sync

	return $EXIT_CODE_OK
}


######################################################
#
#	Start Main() part of script.
#
######################################################

ret=$EXIT_CODE_OK
Initialize

if GetUpgradeInfo
then
	if InstallSoftware
	then
		if CheckInstalledFiles
		then
			if InstallComplete
			then
				LogMessage "Upgrade complete."
			elif [ "$ret" = "$EXIT_CODE_BONE_INSTALLED" ]
			then
				ret=$EXIT_CODE_OK		# Shouldn't have to modify! Change RadarLaunch
				LogMessage "Return code should be $EXIT_CODE_BONE_INSTALLED."
			fi

			if RequestReboot
			then
				# Reboot immediately, assuming all application data has already been saved
				PrintMessage "System is rebooting ... "
#				/bin/shutdown -r -q -d now &
				exit $ret
			fi
		fi
	fi
fi

LogMessage "\nReturn code = ${ret}"
CleanUp
/bin/sync
exit $ret

#
#  End of Script
#