#!/bin/sh
# Nagios shoutcast plug-in
# By Juliano Jeziorny (djkadu@gmail.com)
# Rev 0.1
# 23/11/2010
# *********************************************************
# Modified and adapted for Shoutcast 2 to parse xml stats
# and detect unconnected source
# Rev 0.2 by Keijo D. Putt
# 07-Dec-2017

WARN=128                                # default Warning threshold if none is specified
ALER=96                                 # default Alert threshold if none is specified
SOUR=1                                  # Enable source reporting if none is specified
CURL=`which curl`                       # you can also specify the full path to curl
[[ -z $CURL ]] && exit 3                # if curl is not present exit with unknown error
XML2=`which xml2`                       # We need XML2 to parse the stats output
[[ -z $XML2  ]] && exit 3               # Exit with unknown if we can't find xml2

while getopts ":H:p:w:a:s" OPT; do      # check supplied arguments
       case $OPT in
        H       )       HOST=$OPTARG;;
        p       )       PORT=$OPTARG;;
        w       )       WARN=$OPTARG;;
        a       )       ALER=$OPTARG;;
        s       )       SOUR=$OPTARG;;
       esac
done
if [[ -n $HOST && -n $PORT ]]           # test if minimum required arguments are present
then
       STR=`$CURL http://$HOST:$PORT/stats -A Mozilla/4.0 -s -m 5`      # access stats on the specified host:port
       case $? in
        0       )       ;;
        6       )       echo "Invalid Host"; exit 1;;
        7       )       echo "SHOUTCAST ALERT - Failed to connect to host on port $PORT"; exit 2;;
        *       )       echo "SHOUTCAST UNKNOWN - Unknown error"; exit 3;;
       esac
       STA=`echo $STR | $XML2 | grep /SHOUTCASTSERVER/STREAMSTATUS= | sed 's/.*=//'`           # source connected
       if [[ "$STA" -ne 1 ]] && [[ "$SOUR" -eq 1 ]]
       then
              echo "SHOUTCast CRITICAL - No source connected on port $PORT" ; exit 2           # When source reporting is enabled (1) check will trip if there is no source connected
       fi
       CUR=`echo $STR | $XML2 | grep /SHOUTCASTSERVER/CURRENTLISTENERS= | sed 's/.*=//'`        # current listenens
       MAX=`echo $STR | $XML2 | grep /SHOUTCASTSERVER/MAXLISTENERS= | sed 's/.*=//'`            # max listeners
       TOP=`echo $STR | $XML2 | grep /SHOUTCASTSERVER/PEAKLISTENERS= | sed 's/.*=//'`           # listeners peak
       LEVEL="OK" && EXIT=0                             # if we got to this point with no error assume level is OK
       [[ "$CUR" -ge "$WARN" ]] && LEVEL="WARNING" && EXIT=1    # current listeners higher than warning threshold?
       [[ "$CUR" -ge "$ALER"-1 ]] && LEVEL="ALERT" && EXIT=2    # listeners count higher than alarm threshold?
       echo "SHOUTCast $LEVEL - $CUR out of $MAX listeners (peak: $TOP) on $HOST:$PORT"
       exit $EXIT
fi
echo "Usage:
check_shoutcast -H <ip address> -p <port>
[-w warning level (default 96 listeners)] [-a alert level (default 128 listeners)]"