#!/bin/bash -fp
#
# swup v1.4 2013-08-04, Finn Magnusson, finn.magnusson@ericsson.com
# Type "swup" on its own for help.

###########################################################################################
maxProcess=50    #max number of processes that will run in parallel
timeout=45       #timeout of 45 minutes for upgrade to complete
moshelldir=`dirname "$0"`
if [[ $moshelldir != /* ]] ; then moshelldir=`pwd`/$moshelldir ; fi
logdir="$moshelldir/logfiles/logs_swup"
tempdir="/tmp"
mobatch=$moshelldir/mobatch
swstat=$moshelldir/swstat
moshell=$moshelldir/moshell
vobsinstallation=0
unamea=$(uname -a)
gawkext=""
gawklib=""
if [[ $unamea = [Ll][iI][nN][uU][xX]*x86_64* ]] ; then gawklib="lin64"   ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".lin64" ; fi
elif [[ $unamea = [Ll][iI][nN][uU][xX]* ]]      ; then gawklib="linux"   ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".linux" ; fi
elif [[ $unamea = SunOS*sparc* ]]               ; then gawklib="solaris" ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".solaris" ; fi
elif [[ $unamea = SunOS* ]]                     ; then gawklib="sol86"   ; if [[ $vobsinstallation = 1 ]] ; then gawkext=".sol86" ; fi
else gawklib="cygwin" ; gawkext=".exe"
fi
gawkprog="gawk${gawkext}" 
gawk="$moshelldir/$gawkprog"
#special case where moshell has been installed on a linux 32 bit machine but should be run on linux 64 sharing the same file system
if [[ $unamea = [Ll][iI][nN][uU][xX]*x86_64* && $vobsinstallation != 1 && `file "$moshelldir/gawk"` = *32-bit* ]] ; then gawklib="linux" ; fi
filefunc="$moshelldir/commonjars/lib/${gawklib}/filefuncs"
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH:+${LD_LIBRARY_PATH}:}$moshelldir/commonjars/lib/${gawklib}
export LANG=C
export LC_ALL=C

tempcmdfile="$tempdir/tempcmd$$"
defLogDir=$moshelldir/commonjars/defLogDir.sh
temp_logdir=$($defLogDir swup)
if [[ -w $temp_logdir && -d $temp_logdir ]] ; then logdir=$temp_logdir ; fi
###########################################################################################

function print_date()
{
    echo ""
    date_time=$(date +%y%m%d-%H%M)
    echo ${date_time}: $1 $2
    echo ""
}

function cleanup()
{
	rm $tempcmdfile 
}
trap 'cleanup 2> /dev/null' 0 1 2 3 15 

function print_usage()
{
cat <<EOF
Usage:  swup [option] <sitefile> <sw-file>
	
	Arguments:
	 - The first argument is the sitefile, contains list of site names
	See example in moshell directory: moshell/examples/mobatch_files
	 - The second argument is the sw-file, containing upgrade package info: ftp server address and upcontrolfile path
	 (ftp server userid and password are optional: by default, anonymous is used)
	 See example in moshell directory: moshell/examples/netcheck-swup-cvms/swup_files 
	 
	 IP Database:
	 - The path to IP database must be specified inside the moshell file.
	This file contains the list of all site names and their ip address.	
	See example in moshell directory: moshell/examples/mobatch_files
	
	Options:
	  -r   restart (recommended to do before and after the sw upgrade sequence)
	  -p   make checks before install
	  -i   install and make checks before upgrade (add -h to do a hard install)
	  -u   upgrade and make checks before confirm
	  -c   confirm and make checks before restart
		
     **************************
      Recommended command sequence:
     **************************
	Start with step 1, then step 2. 
	The commands to be executed in following steps will be printed after each step.
	 1) swup -r sitefile           --> a restart before install will increase the upgrade success rate
	 2) swup -p sitefile swfile    --> check if package already installed in some sites.
	                                            New sitefile is created containing only sites where package is not installed.
						    Next command to be executed is printed.
	 3) swup -i sitefile1 swfile   --> soft install (add -h for hard install), then check UP state (should be "installed")
	                                            New sitefile is created containing sites where package is installed.
						    Next command to be executed is printed.
	 4) swup -u sitefile2 swfile   --> upgrade, then check UP state (should be "awaitingconfirm")
	                                            New sitefile is created containing sites where package is awaitingconfirm
						    Next commanad to be executed is printed.
	 5) swup -c sitefile3 swfile   --> confirm, then check UP state (should be "installed")
	                                            New sitefile is created containing sites where package is installed.
	                                            Next command to be executed is printed.
	 6) swup -r sitefile4          --> restart (so that cv loaded and startable become the same)
	
EOF
}

installact="nonblockinginstall"

while getopts "iucrph" options
do
case $options in
p) prepare="1"
   install="0"
   upgrade="0"
   confirm="0"
   restart="0"
  ;;   
i) install="1" 
   upgrade="0"
   confirm="0"
   restart="0"
   prepare="0"
  ;;
h) installact="nonblockingforcedInstall"
  ;;
u) upgrade="1"
   install="0"
   confirm="0"
   restart="0"
   prepare="0"
  ;;    
c) confirm="1"
   install="0"
   upgrade="0"
   restart="0"
   prepare="0"
  ;;
r) restart="1"
   install="0"
   upgrade="0"
   confirm="0"
   prepare="0"
   ;; 
*) print_usage ; exit 1
  ;;
esac
done 
shift $(($OPTIND - 1))
if test $OPTIND -eq 1 ; then print_usage ; exit 1; fi

case $# in
2)  if test $restart -eq 1 ; then print_usage ; exit 1
     else 
	    if test -f "$1" ; then sitefile="$1" ; sitefilename=$(basename $sitefile) ; else echo "Cannot find sitefile. Exiting..." ; exit 1 ; fi
	    if test -f "$2" ; then swfile="$2" ; else echo "Cannot find sw definition file. Exiting..." ; exit 1 ; fi
    fi	    
    ;;    
1)  if test $restart -eq 1 ; then
            if test -f "$1" ; then sitefile="$1" ; sitefilename=$(basename $sitefile) ; else echo "Cannot find sitefile. Exiting..." ; exit 1 ; fi
     else 
           print_usage ; exit 1
     fi	 	     
   ;;
*) print_usage ; exit 1
  ;;   
esac



if test $restart -eq 1 ; then 
	command="acc 0 manualrestart ; 0 ; 0 ; 0"
	echo $mobatch -p $maxProcess $sitefile \"$command\" 
	echo $mobatch -p $maxProcess $sitefile \"$command\" > $tempcmdfile
	echo ""
	chmod 755 $tempcmdfile
	$tempcmdfile
	####
	i=7 #timer to wait for restart to complete: 7 minutes
	until test $i -eq 0 ; do
		echo "$i minutes left before restart complete..."
		i=$(($i-1))
		sleep 60
	done
	echo $swstat $sitefile 
	echo $swstat $sitefile  > $tempcmdfile
	echo ""
	chmod 755 $tempcmdfile
	$tempcmdfile

else 
	upfilepath=$($gawk '/xml/{print gensub("\r","","g",$1)}' $swfile)
	ftpserver=$($gawk 'tolower($0)!~/xml|user|pass/&&$1~/[0-9a-zA-Z]/{print gensub("\r","","g",$1)}' $swfile)
	ftpuserid=$($gawk 'tolower($1) == "user" {print gensub("\r","","g",$NF);found=1} ; END{if (found==0) print "d"}' $swfile)
	ftppassword=$($gawk 'tolower($1) == "password" {print gensub("\r","","g",$NF);found=1} ; END{if (found==0) print "d"}' $swfile)
	#upname=$(basename $upfilepath)
	#upname=$($gawk 'BEGIN{print gensub(/.xml/,"",1,"'$upname'")}')
	#upname=$($gawk 'BEGIN{print gensub("%","/","g","'$upname'")}')
	upname=$($gawk -v upfilepath="$upfilepath" 'BEGIN{last=split(upfilepath,array,"/");if (last>1&&array[last-1]~"CXP")up=array[last-1];else up=gensub(/.xml$/,"",1,array[last]);print gensub(/%/,"/","g",up)}')

	if test $prepare -eq 1 ; then
		echo $swstat -i $upname $sitefile 
		echo $swstat -i $upname $sitefile  > $tempcmdfile
		echo ""
		chmod 755 $tempcmdfile
		$tempcmdfile

	elif test $install -eq 1 ; then
		command="cr swmanagement=1,upgradepackage=$upname ; $ftpserver ; $upfilepath ; $ftpuserid ; $ftppassword ; acc upgradepackage=$upname$ "$installact" ; polu "
		print_date Starting install
		echo $mobatch -p $maxProcess -t 300 $sitefile \'$command\' 
		echo $mobatch -p $maxProcess -t 300 $sitefile \'$command\' > $tempcmdfile
		echo ""
		chmod 755 $tempcmdfile
		$tempcmdfile
	     ######
		echo $swstat -u $upname $sitefile 
		echo $swstat -u $upname $sitefile  > $tempcmdfile
		echo ""
		print_date Finished install
		chmod 755 $tempcmdfile
		$tempcmdfile
		
	elif test $upgrade -eq 1 ; then
		command='ld swmanagement=1,upgradepackage='$upname' ; if $cellomomversion < 4 ; $upaction = upgrade ; else ; $upaction = rebootnodeupgrade ; fi ; acc upgrade $upaction'
		print_date Starting upgrade
		echo $mobatch -p $maxProcess $sitefile \'$command\' 
		echo $mobatch -p $maxProcess $sitefile \'$command\' > $tempcmdfile
		echo ""
		chmod 755 $tempcmdfile
		$tempcmdfile
	     ##########
		echo ""
		i=10 #timer to wait for upgrade to complete: 25 minutes
		echo "Waiting for upgrade(s) to complete..."
		until test $i -eq 0 ; do
			echo "$i minutes left before actively checking..."
			i=$(($i-1))
			sleep 60
		done		
		echo ""
		echo "Launching active check. Please wait for mobatch to return..."
		echo ""
		command='for ever ;  rei ; ld swmanagement=1,upgradepackage='$upname' ; get upgradepackage='$upname' state > $state ; if $state ~ ^[137] ; break ; fi ; wait 180 ; done'
		echo $mobatch -p $maxProcess -t $timeout $sitefile \'$command\' 
		echo $mobatch -p $maxProcess -t $timeout $sitefile \'$command\' > $tempcmdfile
		echo ""
		chmod 755 $tempcmdfile
		$tempcmdfile
#		until test $i -eq 0 ; do
#			echo "$i minutes left before upgrade complete..."
#			i=$(($i-1))
#			sleep 60
#		done
		echo $swstat -c $upname $sitefile 
		echo $swstat -c $upname $sitefile  > $tempcmdfile
		echo ""
		print_date Finished upgrade
		chmod 755 $tempcmdfile
		$tempcmdfile

	elif test $confirm -eq 1 ; then
		command="ld swmanagement=1,upgradepackage=$upname ; acc upgrade confirmUpgrade"
		print_date Starting confirm
		echo $mobatch -p $maxProcess $sitefile \"$command\" 
		echo $mobatch -p $maxProcess $sitefile \"$command\" > $tempcmdfile
		echo ""
		chmod 755 $tempcmdfile
		$tempcmdfile
	     ######
	        #wait for the jvm restart
	        sleep 180  
		echo $swstat -f $upname $sitefile 
		echo $swstat -f $upname $sitefile  > $tempcmdfile
		echo ""
		print_date Finished confirm
		chmod 755 $tempcmdfile
		$tempcmdfile
	fi
fi

