#!/bin/bash

####
# Check Mitel Alarms
# v0.1
####
# Brian Marshall
####
#
# -H is host dns name or address
# -c is snmp community
# -v is snmp version 1 or 2c
#
####

####
# Definitions
####

# Mitel Alarm SNMP OID. Can be updated if it changes

MITELALARMOID="1.3.6.1.4.1.1027.4.1.1.2.2.1.0"

# Check for existance of snmpget in the standard location (prevent malicious user provided scripts dropped in paths)
# Manually change this to the path of your snmpget command

SNMPGETPATH="/usr/bin/snmpget"

if [ ! -f $SNMPGETPATH ]; then
   echo "snmpget doesn't exist in /usr/bin!"
   exit 3
fi

# Process the options, sanitizing the inputs and truncating the string lengths
# If your hostname or snmp community have characters other than alphanumeric, dot, dash and underscore, then you'll need to update the substitutions below

while getopts ":H:c:v:" opt; do
  case $opt in
    H) MITELHOST=$(expr substr "${OPTARG//[^a-zA-Z0-9\.-_]/}" 1 32)
    ;;
    c) MITELCOMMUNITY=$(expr substr "${OPTARG//[^a-zA-Z0-9\._]/}" 1 32)
    ;;
    v) SNMPVERSION=$(expr substr "${OPTARG//[^a-zA-Z0-9]/}" 1 2)
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    exit 1
    ;;
  esac
done

#debug
#echo $MITELHOST
#echo $MITELCOMMUNITY
#echo $SNMPVERSION

# Print help message if there aren't enough options to proceed

if [ -z "$MITELHOST" ]; then
   echo 'check_mitel_alarms.sh : Check Mitel 3x00 systems for alarm status (OK, Minor and Major)'
   echo ''
   echo 'Please specify a host name or address with the -H parameter'
   echo 'Optional parameters are the snmp version and read community with the -v and -c parameters'
   echo 'Version 1 and "public" will be used if unspecified. Only v1 and 2c are supported'

   exit 3
fi

# Provide sane defaults if snmp options aren't specified

if [ -z "$MITELCOMMUNITY" ]; then
   MITELCOMMUNITY="public";
fi

if [ -z "$SNMPVERSION" ]; then
   SNMPVERSION="1";
elif [ "$SNMPVERSION" != "1" ]; then
   SNMPVERSION="2c";
fi

#debug
#echo $MITELHOST
#echo $MITELCOMMUNITY
#echo $SNMPVERSION

# Mitel alarm states are the same as Nagios/Icinga style standard states plus one
# Get the snmp value from the standard OID and use BASH math to reduce it by one when returning the exit code
# All errors are redirected to /dev/null and default in falling through the final "Unknown" state

ALARMSTATE=`$SNMPGETPATH -Oqv -v$SNMPVERSION -c$MITELCOMMUNITY $MITELHOST $MITELALARMOID 2>/dev/null`

if [ ! -z $ALARMSTATE ]; then
   case $ALARMSTATE in
	1)
		echo "OK - No Alarms"
		;;
	2)
		echo "Warning - Minor Alarm"
		;;
	3)
		echo "Critical - Major Alarm"
		;;
	*)
		echo "Unknown - Invalid code returned!"
		exit 3
		;;
   esac
   exit $((ALARMSTATE-1))
else
   echo "Unknown state - Null Code Returned!"
   exit 3
fi
