#!/bin/bash
SERVICE="esia"
PROCESS="esiaDaemon"

mode=$1
num=$2
function exit_error {
	echo $1
	exit 1
}

function test {
	    service $SERVICE status > /dev/null || exit_error "The service $SERVICE isn't running"
	    PROC_NBR=$(ps -FC esiaDaemon --no-headers|tr -s ' ' ' '|grep /usr/local/esia/esiaDaemon|cut -d ' ' -f3|grep "^1$"|wc -l)
        if [ "$PROC_NBR" -ne "1" ]; then
                uptime >> /root/too_much_esia.txt
                ps -FC esiaDaemon >> /root/too_much_esia.txt
                exit_error "They are $PROC_NBR $PROCESS numbers. Must be 1. Uptime : $(uptime -s)."
        fi

		URL=$(cut -d '#' -f1 /etc/esia/esia.conf|grep master_url|head -n 1 |cut -d '=' -f2)
		URL="$URL/health.php";
		DAEID=$(cut -d '#' -f1 /etc/esia/esia.conf|grep daemon_id|head -n 1 |cut -d '=' -f2)
		if [ "$DAEID" -ne "0" ]; then
			URL="$URL?daemonid=$DAEID"
		fi
        #Si health.php n'est pas accessible, on retourne ok, sinon on vérifie le nbre de démons et de services.
	XML=$(wget --no-check-certificate -qO- $URL|tr -s "\n" " "|grep xml) || XML=$(wget --no-check-certificate -qO- https://$URL|tr -s "\n" " "|grep xml) || exit 0
	DAEMONS=$(ps -ae | grep 'esiaDaemon'|grep defunct|wc -l)
        SERVICES=$(echo $XML|sed -e 's#.*<service>\([0-9]*\)</service>.*#\1#g')

        if [ -n $DAEMONS ] && [ $DAEMONS -gt 2 ]; then
                exit_error "$DAEMONS <defunct> daemons are running."
        fi

        if [ -n $SERVICES ] && [ $SERVICES -lt 1 ]; then
                exit_error " Last 5 min execute service: 0."
        fi
}

function rescue {
	case $1 in
		0) echo 1 ;; #Retourne le nombre de modes dispos
		1) service $SERVICE restart || exit_error "service $SERVICE restart FAIL" ;;
		*) exit_error "Unknown rescue num:$1 for service $SERVICE";;
	esac
}

function save {
	echo "save"
}

function load {
	echo "load"
}

case $mode in
	test) test;;
	rescue) rescue $num;;
	save) save;;
	load) load;;
	*) echo "OP 1 must be : [test|rescue|save|load]"; exit 1
esac

exit 0
