#!/bin/bash

##############################################################################################################
##
##  Start Jaguar Server On All Hosts
##
##  ./jaguarstatus_on_all_hosts.sh
##
##  exit code 0: true if all servers running
##       code = N:  N servers not running
##
##############################################################################################################

if [[ ! -f "$HOME/.jaguarhome" ]]; then
	echo "Jaguar has not been installed, quit"
	exit 1
fi

unset LD_LIBRARY_PATH

if [[ ! -f $HOME/.jaguarhome ]]; then
    echo "File $HOME/.jaguarhome not found, exit"
    exit 1
fi

JAGUAR_HOME=`cat $HOME/.jaguarhome`
hostfile="$JAGUAR_HOME/conf/cluster.conf"
allhosts=`cat $hostfile|grep -v '#'|grep -v '@'`

if [[ -f "$hostfile" ]]; then
    ## echo "OK, $hostfile is found"
	/bin/true
else
    echo "$hostfile is not found, exit"
    exit 1
fi

myip=`hostname -I|cut -d' ' -f1`
myips=`hostname -I`
myhost=`hostname`


((rc=0))
((hnum=0))
((good=0))
((bad=0))
badhosts=""
goodhosts=""
echo

for h in $allhosts
do
	((hnum=hnum+1))

    if echo $myips|grep -q $h; then
        #echo "$myhost $myip status" 
        jh=$JAGUAR_HOME
        $jh/bin/jaguarstatus
   	    ecode=$?
    else
        jh=`ssh $h 'if [ -f ~/.jaguarhome ]; then cat ~/.jaguarhome; else echo $HOME/jaguar; fi'`
        #echo "ssh $h jaguarstatus"
        ssh $h "$jh/bin/jaguarstatus"
   	    ecode=$?
    fi

   	### exit code 0 fo true, meaning running.  1 as false for not running
   	((rc=rc+ecode))
   	if ((ecode==0)); then
   		((good=good+1))
   		goodhosts="$goodhosts $h"
   	else
   		((bad=bad+1))
   		badhosts="$badhosts $h"
   	fi
    echo

done

echo
echo "jaguarstatus_on_all_hosts.sh  total hosts=$hnum  jaguar running=$good  stopped=$bad"
if ((bad>0)); then
	echo "Jaguar off hosts: $badhosts"
fi
if ((good>0)); then
	echo "Jaguar on hosts: $goodhosts"
fi
exit $rc

