#!/bin/sh

NEWDIR=/opt/hitachi/serverconductor/agent/newconfig
OLDDIR=/opt/hitachi/serverconductor/agent/work_config
USRDIR=/etc/opt/hitachi/serverconductor/agent

add_member () {
	NEWFILE=$NEWDIR/$1
	OLDFILE=$OLDDIR/$1
	USRFILE=$USRDIR/$1
	
	if [ ! -f $USRFILE ]; then
		cp -p $NEWFILE $USRFILE 2> /dev/null
		diff $NEWFILE $USRFILE > /dev/null 2>&1
		if [ "$?" != "0" ]; then
			rm -f $USRFILE
			#echo "ERROR:   KASM9303S-E: Cannot create the $USRFILE."
			exit 1
		fi
	else
		FORMAT1=`head -n 1 $NEWFILE`
		FORMAT2=`head -n 1 $OLDFILE`
		if [ "$FORMAT1" = "$FORMAT2" ]; then
			case $1 in
			'alert.cfg')
				while read -r LINE
				do
					KEY=`echo "$LINE" | awk '{ print $1 }'`
					if [ $KEY ]; then
						FMTCHECK=`echo "$KEY" | awk -F'x' '{ print $1}'`
						if [ "$FMTCHECK" = "EVENT=0" ]; then
							MATCH=`grep -e "^$KEY" $OLDFILE | awk '{ print $1}'`
							if [ "$MATCH" != "$KEY" ]; then
								echo "$LINE" | cat >> $USRFILE
							fi
						fi
					fi
				done < $NEWFILE
				rm -f $OLDFILE
				;;
			*)
				while read -r LINE
				do
				#	echo "$LINE"
					#5200Z015
					KEY=`echo "$LINE" | awk '$2 == "=" { print $1 }' | awk '{print toupper($1)}'`
					if [ $KEY ]; then
				#3500Z007
						MATCH1=`grep -i -e "^$KEY	" $OLDFILE | awk '{ print $1}' | head -1 | awk '{print toupper($1)}'`
						MATCH2=`grep -i -e "^$KEY " $OLDFILE | awk '{ print $1}' | head -1 | awk '{print toupper($1)}'`
						if [ "$MATCH1" != "$KEY" -a \
							 "$MATCH2" != "$KEY" ]; then
							echo "$LINE" | cat >> $USRFILE
						fi
					fi
				done < $NEWFILE
				rm -f $OLDFILE
				;;
			esac
		fi
	fi
}

chk_copy () {
	cp -p $1 $2 2> /dev/null
	diff $1 $2 > /dev/null 2>&1
	if [ "$?" != "0" ]; then
		rm -f $2
#		echo "ERROR:   KASM9303S-E: Cannot create the $2."
		exit 1
	fi
}

# ecfgt@C}[W
# 6000A570 BMCɂSVP@\(q)}[W
set \
	adagent.cfg \
	svp.cfg \
	snmp.cfg \
	load.cfg \
	svpsub1.cfg \
	svpagent.cfg \
	bmc.cfg
while [ $# -gt 0 ]
do
	CFG_FILE=$1
	if [ ! -f $USRDIR/$CFG_FILE ]; then
		chk_copy  $NEWDIR/$CFG_FILE $USRDIR/$CFG_FILE
		chmod u+w $USRDIR/$CFG_FILE
	else
		mkdir $OLDDIR
		cp -p $USRDIR/$CFG_FILE $OLDDIR/$CFG_FILE
		if [ -d $OLDDIR ]; then
			add_member $CFG_FILE
			rm -rf $OLDDIR
		fi
	fi
	shift
done

#R[0Ԃ(I)
exit 0
