#!/bin/sh

#-----------------Script Actions (Modify at your own risk)-------------------------------

#flash led when starting installation
ccsettingsconsole --led --color=red --frequency=5 --dutycycle=20

# check for identity file
install=0

pattern="VERSION_*"
versionFile="/media/usb/${pattern}"

if [ -e $versionFile ];
then
	echo "Found version file: ${versionFile}"

	installerModelName=$(awk -F " " '/commander_model/ {print $2}' $versionFile)
	installerModelVersion=$(awk -F "=" '/commander_model/ {print $2}' $versionFile)
	
	echo "Found installerModelName in file : ${installerModelName}"
	echo "Found installerModelVersion in file : ${installerModelVersion}"
fi
	
if [ -e /opt/identity ];
then
	echo "Found identity file."

	currentModelName=$(awk -F " " '/commander_model/ {print $2}' /opt/identity)
	currentModelVersion=$(awk -F "=" '/commander_model/ {print $2}' /opt/identity)

	echo "Found currentModelName in file : ${currentModelName}"
	echo "Found currentModelVersion in file : ${currentModelVersion}"
	
	echo "Current model  : $currentModel"
	echo "Installer model: $installerModel"
	
	# model must match model in version file
	if [ "$currentModelName" == "$installerModelName" ];
	then
		version_cmp() { test "$(printf '%s\n' "$@" | sort -n | head -n 1)" != "$1"; }
		
		if version_cmp $installerModelVersion $currentModelVersion ; 		
		then
			echo "Installer model is greater than present $installerModel"
			install=1
		fi 
	fi
else	
	# assume this is a new display.  Proceed with install.
	echo "No identity file."
	echo "commander_model $installerModelName=$installerModelVersion" > /opt/identity
	install=1
fi

if [ $install -eq 1 ];
then
	echo "OK to install."
else
	echo "Not OK to install."
	
	# beep 3 times if fail
	ccsettingsconsole --buzzer --frequency=1000 --volume=40 --status=enable
	sleep 0.2
	ccsettingsconsole --buzzer --frequency=1000 --volume=40 --status=disable
	sleep 0.2
	ccsettingsconsole --buzzer --frequency=1000 --volume=40 --status=enable
	sleep 0.2
	ccsettingsconsole --buzzer --frequency=1000 --volume=40 --status=disable
	sleep 0.2
	ccsettingsconsole --buzzer --frequency=1000 --volume=40 --status=enable
	sleep 0.2
	ccsettingsconsole --buzzer --frequency=1000 --volume=40 --status=disable
	exit

fi

echo "commander_model $installerModelName =$installerModelVersion" > /opt/identity

#Reboot
#echo "Reboot"
#reboot

