#!/bin/sh

IFS='
'
# This patch will try to update the MxD8-script on the unit. There is a bug in early
# script for telegram SetDISettings. The last register, Tripvoltage, is a rword, not a 
# byte.

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"

# 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 (DEVICETYPE)
	#  - TYPEID=21463
	res=$(cat $oldFile | grep DEVICETYPE | grep TYPEID | grep 21463 | wc -l)
		
	if [ "$res" -eq 1 ];
	then
		# Try to find the line that is faulty, i.e. "BYTE(DI_TripVoltage)" 
		tripVoltage=$(cat $oldFile | grep "BYTE(DI_TripVoltage)" | wc -l)
		
		# Check if it is safe to update the old script with the new one
		if [ "$tripVoltage" -eq 1 ]; 
		then
			if [ "$ACTION" == "check" ]; 
			then
				# Inform caller that this patch is needed
				exit 1
			else
				logger "$oldFile needs to be updated"
				
				# Apply the change
				cp $oldFile ./theFiletoPatch
				
				patch ./theFiletoPatch < $THIS_DIR/setDISettings.patch
				
				# Check result
				if [ $? -ne 0 ];
				then
					# Ops, it failed. 
					rm ./theFileToPatch
				  logger "Could not apply patch"
				else
					mv ./theFiletoPatch $oldFile
				fi				
			fi	
		else
			if [ "$ACTION" == "execute" ]; 
			then
				logger "$oldFile is allready updated"
			fi
		fi
	fi
done

exit 0