#!/bin/bash

#Copyright (C) 2017 Thomas Wagner wagner-thomas@gmx.at
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

usage()
{
cat << EOF
This script check via ipmitool if a server is powerd. Useful as master for service dependencies.
OPTIONS:
 -h	Show this message
 -H	IPMI address or hostname
 -U	username
 -P	password
 -I	interface used by ipmitool
 -L     capability
EOF
}

# NAGIOS' wanted return values
NAG_OK=0
NAG_WARN=1
NAG_CRIT=2
NAG_UNKNOWN=3

unset HOST
unset USER
unset PASS
unset CAPA
unset INTERFACE

while getopts ":H:U:P:L:I:h" OPTION
do
	case $OPTION in
	h) 
		usage
		exit $NAG_CRIT
		;;
	H) HOST=$OPTARG
		;;
	U) USER=$OPTARG
		;;
	P) PASS=$OPTARG
		;;
	L) CAPA=$OPTARG
		;;
	I) INTERFACE=$OPTARG
		;;
	?) usage
		exit $NAG_UNKNOWN
	esac
done

RET=$(sudo ipmitool ${INTERFACE+-I ${INTERFACE}} ${HOST+-H ${HOST}} ${USER+-U ${USER}} ${PASS+-P ${PASS}} -L user chassis power status)
if [ $? -eq 0 ] ; then
	if [[ "$RET" = *"off"* ]] ; then
		echo "CRITICAL - Chassis is not powered"
        	RES=$NAG_CRIT
	else
		echo "OK - Chassis is powered"
		RES=$NAG_OK
	fi
else
	echo "UNKOWN - call to ipmitool was not successfull"
	RES=$NAG_UNKNOWN
fi
exit $RES

