#!/bin/sh -f

PATH=$path:/bin:/usr/bin:/usr/ucb

PLACE=".1.3.6.1.4.1.4413.4.1"
REQ=$2
OPTSTR="$1"

if test "$OPTSTR" = "-h"; then
  echo "Usage: gen5820traps -h (help - print this message) | -d (delay) <delaytime - delaytime in seconds>"
  exit 0
elif test "$OPTSTR" = "-d"; then
   if test "$REQ" = ""; then
      DELAYTIME=2
   elif [[ $REQ  > 999999 ]]; then
     echo "Inavlid delay time $REQ. Delay must be between 1 to 999999"
     exit 0
   else
     DELAYTIME=$REQ
   fi
elif test "$OPTSTR" = ""; then
   DELAYTIME=2
else
   echo "Unrecognized option $OPTSTR"
  echo "Usage: gen5820traps -h (help - print this message) | -d (delay) <delaytime - delaytime in seconds>"
   exit 0
fi

echo "Using delaytime = $DELAYTIME"
if ! test -f "/proc/net/bcm5820"; then
   echo "statistics file is not present"
   exit 0
fi

NUMCARDS=`snmpget -m all localhost public $PLACE.1 | awk 'BEGIN { FS = "=" } { print $2 }'`
NUMCARDS=`echo $NUMCARDS`
if test "$NUMCARDS" = ""; then
  echo "snmpget failed. exiting ..."
  exit 0
fi

if test $NUMCARDS > 0; then
  TEMPVAL=$NUMCARDS
  while  expr $TEMPVAL > 0; do
    OLDVALUE[$TEMPVAL]=`snmpget -m all localhost public $PLACE.2.$TEMPVAL.11 | awk 'BEGIN { FS = "=" } { printf $2 }'`
    TEMPVAL=`expr $TEMPVAL - 1`
  done

  if [ -f /usr/share/snmp/snmpd.conf ]; then
     TRAPHOST=`awk '/^trapsink/ { print $2 }' /usr/share/snmp/snmpd.conf`
  elif [ -f /etc/snmp/snmpd.conf ]; then
     TRAPHOST=`awk '/^trapsink/ { print $2 }' /etc/snmp/snmpd.conf`
  fi

  if test "$TRAPHOST" = "";then
     TRAPHOSTS[1]=localhost
     NUMHOSTS=1
  else
     NUMHOSTS=`echo $TRAPHOST | awk 'BEGIN { FS = " " } { print NF }'`
     TEMPVAL=`echo $NUMHOSTS`
     while expr $TEMPVAL > 0; do
       TRAPHOSTS[$TEMPVAL]=`echo $TRAPHOST | awk 'BEGIN { FS = " " } { print $'$TEMPVAL' }'`
       TEMPVAL=`expr $TEMPVAL - 1`
     done
  fi


  while true; do
    TEMPVAL=$NUMCARDS
    while expr $TEMPVAL > 0; do
      NEWVALUE=`snmpget -m all localhost public $PLACE.2.$TEMPVAL.11 | awk 'BEGIN { FS = "=" } { printf $2 }'`
      if [[ ${OLDVALUE[$TEMPVAL]} != $NEWVALUE ]]; then
        if test $NUMHOSTS > 0; then
          TEMPVAL1=$NUMHOSTS
          while expr $TEMPVAL1 > 0; do
            echo "sending trap to ${TRAPHOSTS[$TEMPVAL1]} for crypto dev $TEMPVAL"
            snmptrap -c public ${TRAPHOSTS[$TEMPVAL1]} CryptoNET-Statistics-MIB::cryptonetTrap localhost 6 1 ''\
            CryptoNET-Statistics-MIB::trapAdapterName s "board 1 in slot 1 failed",\
            CryptoNET-Statistics-MIB::trapCauseDirection i 2
            TEMPVAL1=`expr $TEMPVAL1 - 1`
          done
        fi
      fi
      OLDVALUE[$TEMPVAL]=$NEWVALUE
      TEMPVAL=`expr $TEMPVAL - 1`
    done
    sleep $DELAYTIME 
  done
fi
