#!/bin/bash

#############################################################################
##  ./jaguarstop -s      # safe shutdown jaguar server on current host
##  ./jaguarstop         # unsafe shutdown jaguar server on current host
##                       # On Windows servers, it defaults to safesutdown
##  ./jaguarstop -f      # force shutdown jaguar server on current host
##  ./jaguarstop -all    # shutdown jaguar server on all hosts
##  ./jaguarstop -h      # show help menu
#############################################################################

. `dirname $0`/jaguarenv

g_hn=`hostname`
g_ips=""
g_un=`uname -o`

g_apikey=""

g_jql="jql.bin"

function help()
{
	echo
	echo "$0      (unsafe shutdown of jaguar server on current host)"
	echo "$0 -s   (safe shutdown of jaguar server on current host)"
	echo "$0 -f   (force shutdown of jaguar server on current host)"
	echo "$0 -all (shutdown of jaguar server on ALL hosts in the cluster)"
	echo "$0 -h   (show this help menu)"
	echo
}

function localIPs()
{
    g_ips=$(ip -4 addr show \
        | grep inet \
        | awk '{print $2}' \
        | cut -d/ -f1 \
        | grep -v '^127\.')
}


### Wait for all data operations to finish on this server
### This command requires user to enter apikey
function safeShutDown()
{
	echo "Safe shutdown of jaguar server ..."
	localIPs
	iparr=($g_ips)
	numip=${#iparr[@]}
	target=$g_ips
    if ((numip==1)); then
    	echo "Shutting down jaguar server on $target ..."
    else
		LISTEN_IP=`grep LISTEN_IP $JAGUAR_HOME/conf/server.conf |grep -v '#' | awk -F= '{print $2}'`
		if [[ "x$LISTEN_IP" = "x" ]]; then
        	echo "There are multiple IP addresses on this host $g_hn:"
    		echo "$g_ips"
            echo -n "Please enter an IP address: "
            read target
            if [[ "x$target" = "x" ]]; then
            	echo "No server IP address was provided, quit"
            	exit 1
            fi
		else
			target=$LISTEN_IP
		fi
    
    	echo "Shutting down jaguar server on $target ..."
    fi

	port=`grep PORT $JAGUAR_HOME/conf/server.conf |grep -v '#' |grep -v '@' | awk -F= '{print $2}'`

	echo
	echo "OK, shutting down jaguar ..."
	$JAGUAR_HOME/bin/$g_jql -apikey $g_apikey  -h localhost:$port -x yes -m "shutdown $target;"
}

### Send SIGINT to server, let it properly shutdown
### This command does not require user to enter apikey
function unsafeShutDown()
{
	echo "Shutdown of jaguar server on current host $g_hn ..."
	mkdir -p $JAGUAR_HOME/log
	echo "START" > $JAGUAR_HOME/log/shutdown.cmd
	kill -INT $pid  2>/dev/null
	while true
	do
		sleep 5
		val=`cat $JAGUAR_HOME/log/shutdown.cmd`
		if [[ "x$val" = "xSTART" ]]; then
			kill -9 $pid
			break
		elif [[ "x$val" = "xWIP" ]]; then
			if $JAGUAR_HOME/bin/jaguarstatus > /dev/null
			then
				continue
			else
				break
			fi
		else
			break
		fi
	done
}


### Just send SIGKILL to the server
### This command does not require user to enter apikey
function forceShutDown()
{
	echo "Force shutdown jaguar server on current host $g_hn ..."
	kill -9 $pid
}

### Send message to all servers and ask them to stop
### This command requires user to enter apikey
function allShutDown()
{
	echo "Shutdown all jaguar servers in the cluster ..."
	port=`grep PORT $JAGUAR_HOME/conf/server.conf |grep -v '#' |grep -v '@' | awk -F= '{print $2}'`
	echo
	echo "OK, shutting down jaguar on all servers ..."
	$JAGUAR_HOME/bin/$g_jql -apikey $g_apikey -h localhost:$port -x yes -m "shutdown all;"
}


##################### main #############################
echo
if [[ "x$pid" = "x" ]]; then
  	echo "Jaguar server is already shut down on current host $g_hn"
	date
	echo
   	exit 0
fi

##############
JAGUAR_HOME=`cat $HOME/.jaguarhome`
g_apikey=`cat $JAGUAR_HOME/conf/data/superadmin.apikey`
if [[ -z $g_apikey ]]; then
    echo "$JAGUAR_HOME/conf/data/superadmin.apikey is not found, jaguardb cannot be stopped. exit"
    exit 1
fi

cmds=""
i=0
for arg in "$@"
do
	((i=i+1))
    case $arg in
        "-s")
            cmds="-s"
            ;;
        "-f")
            cmds="-f"
            ;;
        "-all")
            cmds="-all"
            ;;
        "-help")
            help
            exit 1
            ;;
        "-h")
            help
            exit 1
            ;;
        *)
            ;;
    esac
done


if [[ "x$cmds" = "x-s" ]]; then
	safeShutDown
elif [[ "x$cmds" = "x-all" ]]; then
	allShutDown
elif [[ "x$cmds" = "x-f" ]]; then
	forceShutDown
elif [[ "x$cmds" = "x-h" ]]; then
	help
else
	if [[ "$g_un" = "Msys" ]]; then
		safeShutDown
	elif [[ "$g_un" = "Cygwin" ]]; then
		safeShutDown
	else
		unsafeShutDown
	fi
fi

date
echo
