#!/bin/bash
#Simple OBS API monitoring script by Thomas Ruecker
#Based on check_sensors 


PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

PROGNAME=`basename $0`
PROGPATH=`echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,'`
REVISION="0.0.3"

LASTEVENTS_ID_OFFSET=10

. $PROGPATH/utils.sh


print_usage() {
	echo "Usage: $PROGNAME"
}

print_help() {
	print_revision $PROGNAME $REVISION
	echo ""
	print_usage
	echo ""
	echo "This plugin checks availability of OpenBuildService API."
	echo ""
	support
	exit 0
}

case "$1" in
	--help)
		print_help
		exit 0
		;;
	-h)
		print_help
		exit 0
		;;
	--version)
   	print_revision $PROGNAME $REVISION
		exit 0
		;;
	-V)
		print_revision $PROGNAME $REVISION
		exit 0
		;;
	*)
		#Pull lastevents for the given hostname
		LASTEVENTS=`curl --connect-timeout 45 -s  https://$ICINGA_HOSTNAME/public/lastevents`

		#If returncode is non-zero something went wrong and play safe.
		if [ "$?" -ne "0" ]; then
			echo "Host seems down!"
			exit 2
		fi

		#Pull an event a bit earlier than the last one, the offset of 10 is arbitrary.
		if `curl -s "https://$ICINGA_HOSTNAME/public/lastevents?start=$(echo $(( $(echo $LASTEVENTS | cut -f2 -d'"') - 10 )))" | grep -q "remote error"`; then 
			echo Public API down
			exit 2 
		else 
			echo Public API up
			exit 0
		fi
		;;
esac
