#!/bin/sh

IFS='
'
# This patch will try to update the ExM28-script on the unit. Early script did not
# conatain information about "MUNIT" which resulted in that is was not possible to
# select sensor definition for UI's, e.g. PT1000-definition.

THIS_DIR=$(dirname "$0")

# What to do: check if this patch is needed or actually applying it...
ACTION=$1

SCRIPT_DIR="/usr/local/www/default/files/comdefs"
SCRIPT_NAME=IMSE_ExM28_AeACom.ups
NEW_SCRIPT="$THIS_DIR/$SCRIPT_NAME"

# Try to find the old script file
for oldFile in $SCRIPT_DIR/* ;
do
	# Do not bother about directories...
	if [ -d "$oldFile" ];
	then
		continue
	fi
	
	# Check for:
	#	 - correct script type (AEADEVICE)
	#  - TYPEID=64002
	res=$(cat $oldFile | grep AEADEVICE | grep TYPEID | grep 64002 | wc -l)
		
	if [ "$res" -eq 1 ];
	then
		# Find of how many lines that differ between the old and the new script
		# This is one of the few ways to guess the version of the old script
		numChangedLines=$(diff $oldFile $NEW_SCRIPT | grep "^+" | wc -l)

		# Find out if the old script contains the MUNIT-text
		numMUNIT=$(cat $oldFile | grep "MUNIT" | wc -l)

		# Check if it is safe to update the old script with the new one
		if [ "$numChangedLines" -eq 48 ] && [ "$numMUNIT" -ne 8 ]; 
		then
			if [ "$ACTION" == "check" ]; 
			then
				# Inform caller that this patch is needed
				exit 1
			else
				logger "$SCRIPT_NAME needs to be replaced"
				cp $NEW_SCRIPT $oldFile
			fi	
		else
			if [ "$ACTION" == "execute" ]; 
			then
				logger "$SCRIPT_NAME is allready updated"
			fi
		fi
	fi
done

exit 0