#!/bin/bash

APPNAME=$(basename $0)

#PREREQUISITE
binaries=$(cat<<all_required_binaries
  /usr/sbin/clustat
all_required_binaries)

for required_binary in $binaries; do
  which $required_binary > /dev/null
  if [ "$?" != '0' ];then
    printf "UNKNOWN: $APPNAME: Packet '$required_binary' manquant dans la variable '$PATH'\n"
    exit 3
  fi
done

#HELP:
usage () {
cat<<EOU
Usage of $APPNAME
---------------------------------------------------------------------

clustat -- antoine meme version 1.0
www.blogvirtualisation.com
antoine.meme@gmail.com
17/12/2009

Options:
  -s
     nom du service en cluster. plus d'infos avec la commande clustat.
  -n
     nom de l'autre noeud en cluster plus d'infos avec la commande clustat
  -h
     Afficher ce message d'aide.

Examples:
  $APPNAME -s NOMDUSERVICE
  $APPNAME -n NOMDUNOEUD
---------------------------------------------------------------------
EOU
exit 3
}

#ARG:

while getopts "s:n:h" option
do
	case $option in
  		s ) service=$OPTARG ;;
		n ) node=$OPTARG ;;
		h ) usage ;;
	esac
done

# VERIF ARG:
if [ -z $service ] && [ -z $node ];then
        echo -e "Error: argument manquant. taper -h pour voir l'aide"
        exit 3
fi

# IF SERVICE :
if [ -n $service ] && [ -z $node ];then

	#VALUE:
	clustatservice=`sudo /usr/sbin/clustat -s $service | grep $service | awk '{print $3}'`
	node=`sudo /usr/sbin/clustat -s $service | grep $service | awk '{print $2}'`


	#MAIN:
	if [ -z $clustatservice ]; then
        	echo "service $service not found";
	        exit 3;
	elif [ $clustatservice = "started" ]; then
		echo "OK cluster $service started on $node";
		exit 0;
	elif [ $clustatservice = "pending" ]; then
		echo "CRITICAL cluster $service pending on $node"
		exit 1;
	elif [ $clustatservice = "disabled" ]; then
        	echo "CRITICAL cluster $service disabled on $node"
	        exit 1;	
	elif [ $clustatservice = "stopped" ]; then
        	echo "CRITICAL cluster $service stopped on $node"
	        exit 1;
	elif [ $clustatservice = "failed" ]; then
        	echo "CRITICAL cluster $service failed on $node"
	        exit 2;
	else
		echo "UNKNOW";
		exit 3;
	fi

# IF NODE :
elif [ -z $service ] && [ -n $node ]; then

	#VALUE :
	stateclustatnode=`sudo /usr/sbin/clustat | grep -m 1 $node | awk '{print $3}' | tr -d ','`
	namenode=`sudo /usr/sbin/clustat | awk '{print $1}' | grep $node`

	#MAIN :
	if [ -z $namenode ]; then
		echo "cluster node $node not found"
		exit 3
	elif [ $stateclustatnode = "Online" ]; then
		echo "$namenode is Online"
		exit 0
        elif [ $stateclustatnode = "Offline" ]; then
                echo "$namenode is Offline"
                exit 2 
	else 
		echo "UNKNOW"
		exit 3
	fi
fi

