#!/bin/bash

# cubiclegraffiti.net 2012-03-23

# This script provides the number of Minecraft users logged into the target Minecraft server. 

# This script requires: 
# 1) Download and install Dinnerbone's mcstatus scripts cli.py and minecraft_query.py, 
#    found here: https://github.com/Dinnerbone/mcstatus
# 2) Set MC_SERVER_PORT variable if the Minecraft server port on target server differs
#     from default of 25565
#    ***NOTE:MC_SERVER_PORT is UDP, not TCP as the minecraft client connections are, which
#          means that you may need to open this port in your firewall config
# 3) On your MineCraft server, set enable-query=true in server.properties 
# 4) Set MC_QUERY_CLI_LOC variable with name and location of cli.py script

# In Nagios command.cfg:
# define command{
#        command_name    check_minecraft_users
#        command_line    $USER1$/check_minecraft_users_cacti_nagios.sh $HOSTADDRESS$ $ARG1$ $ARG2$ nagios
#        }

# In Nagios services.cfg
#define service{
#        use                             service_1_min       
#        host_name                       remotehost1,remotehost2
#        service_description             minecraft users
#        check_command                   check_minecraft_users!15!20
#        max_check_attempts              7
#        contact_groups                  admins
#        }
#
# For Cacti, you will likely need to change the path in the 
# Data Input Method for minecraft_users_connected to match your systems

MC_SERVER_PORT="25565"
MC_QUERY_CLI_LOC="/usr/local/nagios/libexec/minecraft_query_cli.py"

        if [[ -z $1 ]]
        then
                echo "Usage"
                echo "For Cacti: ./check_minecraft_users_cacti_nagios.sh <ipaddress>"
                echo "For Nagios: ./check_minecraft_users_cacti_nagios.sh <ipaddress> <numeric_warning_threshold> <numeric_critical_threshold> nagios"
                echo "Example: ./check_minecraft_users_cacti_nagios.sh 127.0.0.1 15 20 nagios"
                exit 3
        fi

COUNT=$($MC_QUERY_CLI_LOC $1 | grep numplayers | awk '{print $2}' | cut -d "," -f 1)

        if [[ -z $COUNT ]]
        then
		DATACHECK=$(../check_tcp -H $1 -p $MC_SERVER_PORT)
		if [[ -z $DATACHECK ]]
		then
			echo "No data. Connectivity Problem or Minecraft Server not running?"
			exit 3
		fi
	fi

 
	if [[ $4 == "nagios" ]]
	then

		if [[ ${COUNT} -lt $2 ]]
        	then
                	echo "OK - $COUNT users."
                	exit 0
		elif  [[ ${COUNT} -ge $2 ]]
        	then
          	      if  [[ ${COUNT} -ge $3 ]]
                        then
                        echo "CRITICAL - Alert threshold set to $3, currently $COUNT users logged in."
                        exit 2
                	else
                        echo "WARNING - Alert threshold set to $2 users - currently $COUNT users logged in."
                        exit 1
                	fi
        	fi
	else
		echo "users:$COUNT"
		exit 0
	fi

exit 3

