#!/bin/bash

##############################################################################################################
##
##  Stop Jaguar Server On All Hosts
##
##  ./jaguarstop_on_all_hosts.sh
##
##############################################################################################################

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

echo

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

myips=`hostname -I`

arr=($allhosts)
numhosts=${#arr[@]}
#echo "there are $numhosts hosts hosts=[$allhosts]"
for h in $allhosts
do
    if echo $myips|grep -q $h; then
        jh=$JAGUAR_HOME
        echo "$h jaguarstop"
        $jh/bin/jaguarstop
    else
        jh=`ssh $h 'if [ -f ~/.jaguarhome ]; then cat ~/.jaguarhome; else echo $HOME/jaguar; fi'`
        echo "ssh $h jaguarstop"
        ssh $h "$jh/bin/jaguarstop" &
    fi
done
wait
sleep 5


### wait until all jaguars have been stopped
((cnt=1))
while true
do
	$JAGUAR_HOME/bin/jaguarstatus_on_all_hosts.sh
	notrunning=$?
    echo "$JAGUAR_HOME/bin/jaguarstatus_on_all_hosts.sh (Total number of stopped servers is $notrunning)"
	((running=numhosts-notrunning))
	if (( running > 0 ))
	then
		date
	    echo "There are still $running jaguar servers running, wait ..."
	    sleep 5
		if (( cnt == 10 )); then
            echo 
            echo "Try to stop servers  ..."
			for h in $allhosts; do
                if echo $myips|grep -q $h; then
                    jh=$JAGUAR_HOME
                    echo "$h jaguarstop"
                    $jh/bin/jaguarstop
                else
                    jh=`ssh $h 'if [ -f ~/.jaguarhome ]; then cat ~/.jaguarhome; else echo $HOME/jaguar; fi'`
    		        ssh $h "$jh/bin/jaguarstop" &
                fi
			done
            wait
            ## reset cnt to 1
			((cnt=1))
		fi
		((cnt=cnt+1))
	else
		break
	fi
	
done

echo "Jaguar database server has been stopped on all $numhosts hosts"

