#!/bin/sh

CHOME=/usr/local/controller

insertAlarm() {
	in_id=$1
	in_status=$2
	in_raised=$3
        time=`date +%s%N`
        time=$(($time/1000000))

	echo "insert into Alarms(time, id, status, raised) values ($time, $in_id, $in_status, $in_raised)" \
		| mysql -usatis -psatis satis
	echo "insert into Alarms(time, id, status, raised, sync) values (0, $in_id, $in_status, $in_raised, -1) on duplicate key update raised = $in_raised" \
		| mysql -usatis -psatis satis
}


#main
special=0
read host
read ip
ip=`echo $ip | sed 's/\([^0-9.]*\)\([0-9.]*\).*/\2/'`
vars=
status=0

id=`echo "select NodeID from SystemConf where (Name = 'Address' or Name = 'IPAddress') and Value='$ip'" | mysql -usatis -psatis satis | tail -n 1`

if [ "$id" == "" ]
then
	echo trap: $1 $host $ip -- no ID found for this host >> /tmp/trap.log
	id=-1
	#exit 1
fi

while read oid val
do
  if [ "$vars" = "" ]
  then
    vars="$oid = $val"
  else
    vars="$vars, $oid = $val"
  fi
  
  #device specific section, CDM625
  if [[ $oid == *enterprises.6247.34.* ]]
  then
  	special=1
  	. $CHOME/scripts/trap-processors/cdm625.sh
  	processCDM625
  fi

  #device specific section, CDM625A
  if [[ $oid == *enterprises.6247.80.* ]]
  then
        special=1
        . $CHOME/scripts/trap-processors/cdm625a.sh
        processCDM625A
  fi

  #device specific section, CDM570
  if [[ $oid == *enterprises.6247.24.* ]]
  then
  	special=1
  	. $CHOME/scripts/trap-processors/cdm570.sh
  	processCDM570
  fi
  
  #device specific section, DEV1951
  if [[ $oid == *enterprises.21035.41.3.4.1.5.* ]]
  then
        special=1
        . $CHOME/scripts/trap-processors/dev1951.sh
        processDEV1951
  fi

  #device specific section, MDM6000
  #alarm oid value
  if [[ $oid == *.5835.5.3.2.1.1.7.* ]]
  then
  	special=1
	event=$val
  fi

  #alarm status (0/1)
  if [[ $oid == *.5835.5.3.2.1.1.9.* ]]
  then
  	special=1
  	. $CHOME/scripts/trap-processors/mdm6000.sh
  	processMDM6000 $event $val
  fi
  #end of MDM6000

  #device specific section, AZ202
  if [[ $oid == *.5835.3.202.1.2.4.* ]]
  then
  	if [[ $oid == *.202.1.2.4.2.* ]]
  	then
  		if [[ $oid = *.202.1.2.4.2.1.0 ]]
  		then
  			status=$val
  			continue
  		fi
  		if [[ $oid = *.202.1.2.4.2.8.0 ]]
  		then
  			group=$val
  			continue
  		fi

		etype=$oid
		event=$val

  		special=1
  		. $CHOME/scripts/trap-processors/az202.sh
  		processAZ202 $etype $event $status $group
  	fi
  fi
  #end of AZ202
done

#echo trap: argument = $1, host = $host, ip = $ip >> /tmp/trap.log
#echo trap: $1 $host $ip $vars >> /tmp/trap.log

if [ "$special" == "0" ]
then
	echo unhandled trap: $1 $host $ip $vars >> /tmp/trap.log	
fi

killall -HUP alarm

