#!/bin/bash

##############################################################################################################
##
##  Server Installation Script  -- Install Jaguar Database on All Hosts in HOSTSFILE
##
##  ./install_jaguar_database_on_all_hosts.sh  -f <HOSTSFILE>  (Install to $HOME directory)
##  ./install_jaguar_database_on_all_hosts.sh  -f <HOSTSFILE>  [-d <INSTALL_DIR>]  (Install to INSTALL_DIR)
##
##############################################################################################################

function usage()
{
    echo "Usage: ./install_jaguar_database_on_all_hosts.sh [OPTION] -f HOSTFILE"
    echo "Install JaguarDB on all hosts specified by -f HOSTFILE"
    echo "  [-help]           Display help text and exit."
    echo "  [-d DIRECTORY]    Install Jaguar in DIRECTORY. " 
    echo "                    If not provided, Jaguar will be installed in $HOME directory"
    echo "  [-f HOSTFILE]     Install Jaguar database on all the hosts in HOSTFILE."
    echo " "
    echo "In the HOSTFILE, each line must contain a host IP address."
    echo " "
    echo "Example of HOSTFILE:"
    echo "192.168.1.101"
    echo "192.168.1.102"
    echo "192.168.1.103"
    echo "192.168.1.104"
    echo " "
    echo "All host IPs must be unique in the HOSTFILE."
}

unset LD_LIBRARY_PATH
date


dname=`dirname $0`
if [[ "x$dname" = "x." ]] ; then
    dname=`pwd -P`
fi


updir=`dirname $dname`
ver=`basename $dname`

tarfile="${ver}.tar.gz"
tarpathfile="${updir}/$tarfile"

echo "Archive file name: $tarfile"
echo "Archive file full path: $tarpathfile"

jaguarhome=$HOME/jaguar

dirInstall=""
options=""
arggivenfile=""
if [[ ! -f "$tarpathfile" ]]; then
	echo "$tarpathfile is not found, exit"
	exit 1
fi

#echo "tarfile=[$tarfile] tarpathfile=[$tarpathfile]"
## Traverse all options given for this shell script
i=0
for arg in "$@"
do
    i=`expr $i + 1`
    case $arg in
        "-f")
            i_next=`expr $i + 1`
            if [[ $i_next -le $# ]]; then
                    arggivenfile=${!i_next}
					if [[ ! -f "$arggivenfile" ]]; then
						echo "Error $arggivenfile does not exist, exit"
                        usage
						exit 1
					fi
            else
				echo "Error You have not provided -f hostfile"
				echo "exit...."
                echo
				usage
               	exit 1
            fi
            ;;

        "-d")
            i_next=`expr $i + 1`
            if [ $i_next -le $# ]
            then
                jaguarhome=${!i_next}
            else
				usage
                exit 1
            fi
            ;;
        "-help")
            usage
            ;;
        "-h")
            usage
            ;;
        *)
            i_previous=`expr $i - 1`
            if [ ${!i_previous} != "-f" -a ${!i_previous} != "-d" ]
            then
            	usage
                exit 1
            fi
            ;;
    esac
done


JAGUAR_HOME=$jaguarhome
if [[ -e "$JAGUAR_HOME" ]]; then
    echo "OK, install jaguar files to $JAGUAR_HOME ..."
	echo $JAGUAR_HOME > $HOME/.jaguarhome
else
    echo "JAGUAR_HOME $JAGUAR_HOME does not exist, create it ..."
	if ! mkdir -p $JAGUAR_HOME; then
		echo "Error Unable to mkdir $JAGUAR_HOME"
        usage
		exit 1
	fi
fi

if [[ "x$JAGUAR_HOME" = "x$HOME" ]]; then
	echo "Wrong JAGUAR_HOME $JAGUAR_HOME exit"
	exit 1
fi

/bin/mkdir -p $JAGUAR_HOME/conf
/bin/mkdir -p $JAGUAR_HOME/data
/bin/mkdir -p $JAGUAR_HOME/bin/tools

clusterconffile="$JAGUAR_HOME/conf/cluster.conf"
myip=`hostname -I|cut -d' ' -f1`
myips=`hostname -I`

if [[ -f "$clusterconffile" ]]; then
    ((firstTime=0))
    if [[ "x$arggivenfile" != "x" ]]; then
        echo "Error Jaguar databaser server has been installed, no -f HOSTFILE is allowed"
        exit 123
    fi
else
    ((firstTime=1))

    if [[ "x$myip" = "x" ]]; then
        echo "127.0.0.1" > $clusterconffile
    else
        echo "$myip" > $clusterconffile
    fi

    echo "firstTime true cluster file =[$clusterconffile] ..."
fi

### save ssh setup flag
curd=`pwd`
cd $dname
if [[ ! -f "$HOME/.jagsetupssh" ]]; then
    echo "Have you setup the ssh public keys on all the hosts? If yes, please enter y. Otherwise enter n, and here they will be setup now."
    read yn
    if [[ "x$yn" = "xy" ]]; then
        echo "OK, I assume you already created your private and public key pair, and distributed your public key to all remote hosts."
        echo "If any connection issues occur, please finish the setup or enter n here to do the setup now."
		echo done > $HOME/.jagsetupssh
    else
	    echo "Set up ssh public keys on all hosts ... (I assume the same password is used on all those remote hosts)"
	    if $dname/setupsshkeys -f $clusterconffile; then
		    echo done > $HOME/.jagsetupssh
	    fi
    fi
fi
cd $curd

### unpack new tar to ~/jaguardownload 
mkdir -p $HOME/jaguardownload
/bin/cp -f $tarpathfile $HOME/jaguardownload/
cd $HOME/jaguardownload
tar --warning=no-timestamp -zxf $tarfile
cd $ver
/bin/cp -f server/jaguarstop_on_all_hosts.sh $JAGUAR_HOME/bin/
/bin/cp -f server/jaguarstatus_on_all_hosts.sh $JAGUAR_HOME/bin/
/bin/cp -f server/jaguarstart_on_all_hosts.sh $JAGUAR_HOME/bin/
/bin/cp -f server/jaguarenv $JAGUAR_HOME/bin/
/bin/cp -f server/jaguarstop $JAGUAR_HOME/bin/
/bin/cp -f server/jaguarstart $JAGUAR_HOME/bin/
/bin/cp -f server/jaguarstatus $JAGUAR_HOME/bin/
/bin/cp -f server/tools/*  $JAGUAR_HOME/bin/tools/
cd $curd

### copy jaguarstop to all hosts
allhosts=`grep -v '#' $clusterconffile |grep -v '@'| awk '{print $1}' `
((hasExternal=0))
for h in $allhosts; do
    if echo $myips |grep -q $h; then
        jh=$JAGUAR_HOME
        echo "Done copy basic scripts on local host $h to jaguar home directory: $jh"
    else
        jh=`ssh $h 'if [ -f ~/.jaguarhome ]; then cat ~/.jaguarhome; else echo $HOME/jaguar; fi'`
        echo "Copy basic scripts to host $h to jaguar home directory: $jh ..."
    	ssh $h "/bin/mkdir -p $jh/bin"
    	scp $JAGUAR_HOME/bin/jaguarenv $h:$jh/bin/ &
        sleep 1
    	scp $JAGUAR_HOME/bin/jaguarstop $h:$jh/bin/ &
        sleep 1
    	scp $JAGUAR_HOME/bin/jaguarstatus $h:$jh/bin/ &
        sleep 1
    	scp $JAGUAR_HOME/bin/jaguarstart $h:$jh/bin/ &
        sleep 1
        ((hasExternal=1))
   fi 
done

((hasExternal==1)) && wait
echo "Done copying basic scripts"
echo


### stop all servers first
if [[ -f "$JAGUAR_HOME/bin/jaguarstop_on_all_hosts.sh" ]]; then
	echo "Stop Jaguar on all hosts ..."
	echo "$JAGUAR_HOME/bin/jaguarstop_on_all_hosts.sh"
	$JAGUAR_HOME/bin/jaguarstop_on_all_hosts.sh
	echo "======================================================"
	sleep 5

fi

### Install Jaguar on all hosts
echo
echo "Install Jaguar on all hosts ..."

for h in $allhosts
do
  if echo $myips |grep -q $h; then
      echo "Copy $tarpathfile to $HOME/jaguardownload"
      mkdir -p $HOME/jaguardownload
      /bin/cp -f $tarpathfile $HOME/jaguardownload/
  else
      ssh $h "mkdir -p ~/jaguardownload"
      echo "copy $tarpathfile to $h:~/jaguardownload/ ..."
      scp $tarpathfile $h:~/jaguardownload/ &
      sleep 1
    fi
done
((hasExternal==1)) && wait
echo "Done copying $tarpathfile to all hosts"
echo

for h in $allhosts
do
   if echo $myips |grep -q $h; then
        echo "Copy $tarpathfile to $HOME/jaguardownload"
        jh=$JAGUAR_HOME
        echo "Run install.sh on local host $myip from $jh ..."

        cd ~/jaguardownload; tar --warning=no-timestamp -zxf $tarfile; cd $ver; ./install.sh -d $jh 

        sleep 1
        echo

   else
        jh=`ssh $h 'if [ -f ~/.jaguarhome ]; then cat ~/.jaguarhome; else echo $HOME/jaguar; fi'`
    
        echo "Run install.sh on host $h to jaguar home directory: $jh ..."
    
        if (( firstTime==1)); then
    	    scp $clusterconffile $h:$jh/conf/
        fi

        ssh $h "mkdir -p $jh; cd ~/jaguardownload; tar --warning=no-timestamp -zxf $tarfile; cd $ver; ./install.sh -d $jh" &

        sleep 1
        echo
  fi
done
((hasExternal==1)) && wait 
echo "Done uncompressing package and installing on all hosts"
echo "======================================================"


### check programs and settings
if [[ -f "$JAGUAR_HOME/bin/tools/check_binaries_on_all_hosts.sh" ]]; then
    echo
    echo "Check program binaries on all hosts ..."
    if $JAGUAR_HOME/bin/tools/check_binaries_on_all_hosts.sh; then
    	echo "Program binaries are checked, please verify they are OK"
    else
    	echo "Program binaries have problem, exit"
    	echo "Please update jaguar.bin jql.bin"
    	exit 1
    fi
    echo "======================================================"
    echo
    
    echo "Check PORT on all hosts ..."
    $JAGUAR_HOME/bin/tools/check_config_on_all_hosts.sh PORT 
    echo "======================================================"
    echo
    
    echo "Check SERVER_TOKEN on all hosts ..."
    $JAGUAR_HOME/bin/tools/check_config_on_all_hosts.sh SERVER_TOKEN
    echo "======================================================"
    echo
    
fi


if [[ -f "$JAGUAR_HOME/bin/jaguarstart_on_all_hosts.sh" ]]; then
    echo
	echo "Finally start Jaguar on all hosts ..."
	echo "$JAGUAR_HOME/bin/jaguarstart_on_all_hosts.sh"
	$JAGUAR_HOME/bin/jaguarstart_on_all_hosts.sh
    date
    echo
fi

