#!/bin/bash
############################################
# Script for writing into the error file
# Usage: ./dtb-error error_message  
#
# rpm73(SLES15) - initial creation
############################################

# Import definitions
CMD=$(basename $0)
if [ -f /opt/dtb/bin/_common_definitions ]; then
	. /opt/dtb/bin/_common_definitions
else
	logger -t $CMD -p ERROR -s "The /opt/dtb/bin/_common_definitions file does not exist, exiting the script..."
	exit 1
fi

plog "Getting error: $1"
message="$(echo "$1" | sed 's/_/ /g')"

ErrorFile=$DTB_CFGDIR/errorFile

#The message starts with <errorCode>000</errorCode>, the cod can be from 000 to 999
#To avoid duplicate messages we use this code to verify if it is already added
	#If not, then we add the error message
	#If yes, then we replace the error message, to have the latest timestamp.

errorCode=${message:11:3}
plog "The error code is $errorCode";

if [ ! -f $ErrorFile ]; then
	plog "errorFile doesn't exist! Creating it..."
	plog "Writing error: $message"
	echo $message >> $ErrorFile
	chmod -R 777 $ErrorFile
else
	if grep -q "<errorCode>$errorCode</errorCode>" "$ErrorFile"; then
		plog "The code $errorCode is already present in the error File. Replacing the message..."
		#prepare the text for the replace: escape the backslashes
		sed -i "s|<errorCode>$errorCode</errorCode>.*|$message|g" $ErrorFile
		plog "Replaced with: $message"
	else
		plog "Writing new error: $message"
		echo $message >> $ErrorFile
	fi
fi

exit 0
