#!/bin/bash
#
#########################################################################################
# Script: 		unattended_deploy.sh
# Description: 	Unattended ABSMENU procedures
# Author: 		ABS Laundry Business Solutions
# Version: 		4.5
#### Changelog of script ################################################################
# Date        Author    Version 	Change    
# 31-Jan-2018 MBU		2.2			Initial version
# 12-Sep-2018 MBU		2.3			Added features (start,stop,restart,update,restore,deploy
#									reports,license,properties,version)
# 28-Sep-2018 MBU		2.7			Added features (patching, unpack)
#									Move SQL script to completed directory in repository after successful deploy
# 27-Dec-2018 MBU		3.0			Bugfix: Remove old sql scripts when unpack update package
#									Added unpack WRD (webclientresidentialdelivery_*.war)
#									Clear Server/lib and Reportserver/lib before unpack update package
#									Extended unattended scriptrun with error handling by sqscript log
# 07-Feb-2019 MBU		3.2			Bugfix: Unpack patch 9.03.00.RELEASE.px deletes future repository
# 26-Mar-2019 MBU		3.3			Added unpack WUA (webclientmyuniformassistant_*.war)
#									Added unpack WRR (webclientroutereturns_*.war)
# 04-Apr-2019 MBU		4.0			Added heapspace sync command
#									Added syncabsshell option to push abs.sh to middle-tier server
#									Added upgraderegistration4 to add missing column in service_registation.cfg
#									Added beautifyregistration to order columns in service_registation.cfg
#########################################################################################

#### Functions ####################################################################

logline()
{
	# Output $1 to logfile
    if [ "$DOABSLOGGING" == "yes" ]
    then
        echo -n $(date +%T) >> $ABSMSCRIPTLOGNAME
        echo "  $1" >> $ABSMSCRIPTLOGNAME
    fi
}

unattendedCheckFile()
{
	# When the UNATTENDED_FILE variable is not given or the file does not exists
	if [ -z $UNATTENDED_FILE ] || [ ! -f $UNATTENDED_FILE ]
	then			
		logline "The given file $UNATTENDED_FILE does not seem to exist."
		unattendedExit
	fi
}

unattendedSetGLASSFISHPATH()
{
	# Create glassfish filepath
	export ABSSOLUTENUMVERSION=`echo $ABSMENU_FUTURE_ENV_SERVERJAR_VERSION | sed 's/\(.\)\.\(..\)\.\(..\).*/\1\2\3/'`
	if [ $ABSSOLUTENUMVERSION -ge 90400 ]
	then
		export GLASSFISHPATH="payara5"
	else
		if [ $ABSSOLUTENUMVERSION -ge 90000 ]
		then
			export GLASSFISHPATH="glassfish4"
		else
			export GLASSFISHPATH="glassfishv3"
		fi
	fi
}

unattendedExit()
{
	# Default error message when exiting the UNATTENDED scriptrun
	logline "WARNING: The UNATTENDED scriptrun will exit now."
	exit 1
}

unattendedProcessABSSoluteFile()
{
	# Check if the UNATTENDED_FILE exists
	unattendedCheckFile
	
	# Place the patch in the repository
	case $UNATTENDED_FILE in
	*Update_Linux_*.zip) 
		logline "Unpack the update package $UNATTENDED_FILE to the future repository for deployment."
		# Remove the Server patch jars from the previous version
		rm $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/Lib/patchserver*.jar
		# Clear sqlscripts directory
		rm -r $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts/*
		# Clear lib directories
		rm $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/Lib/*
		rm $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Reportserver/Lib/*
		# Extract the update package to the repository
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future";;
	*Patch_*.zip) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the ABSSolute patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future"
		export UNATTENDED_PATCHDIRNAME=$(echo $UNATTENDED_FILE | grep -Eo 'Patch_[[:digit:]]{1}.[[:digit:]]{2}.[[:digit:]]{2}.[[:alnum:]]{1,10}.[[:alpha:]]{1}[[:digit:]]{2}')
		mv $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/ReportServer $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Reportserver
		
		# Move script directories to sqlscripts subdirectory of future repository
		mkdir -p $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Server/sqlscripts
		find $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME -type d -name "_*_sql" -exec mv {} $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Server/sqlscripts \; > /dev/null 2>&1

		# Delete patch release notes
		rm $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Patch\ Release\ Notes.txt
		
		# Remove already ran patch scripts
		if [ "$ABSMENU_CURRENT_ENV_SERVERJAR_VERSION.$ABSMENU_CURRENT_ENV_SERVERJAR_REVISION" = "$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION.$ABSMENU_FUTURE_ENV_SERVERJAR_REVISION" -a $(echo $ABSMENU_CURRENT_ENV_PATCHSERVERJAR_VERSION | rev | head -c2 | rev) != "-" ] 
		then 
			export currentpatch=$(echo $ABSMENU_CURRENT_ENV_PATCHSERVERJAR_VERSION | rev | head -c2 | rev)
			[ ${currentpatch:0:1} == "0" ] && export currentpatch=${currentpatch:1:1}
			for (( c=1; c<=$currentpatch; c++ ))
			do
				if [ $c -lt 10 ]
				then
					[ -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Server/sqlscripts/_p_0$(echo $c)_sql ] && rm -r $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Server/sqlscripts/_p_0$(echo $c)_sql
				fi
				[ -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Server/sqlscripts/_p_$(echo $c)_sql ] && rm -r $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/Server/sqlscripts/_p_$(echo $c)_sql
			done
		fi
		
		# Sync patch libraries and reports with normal repository directory
		find $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts -type d -name "_*_sql" -exec rm -rf {} \; > /dev/null 2>&1
		rsync -a $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME/* $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future
		rm -r $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/$UNATTENDED_PATCHDIRNAME;;
	*absgenericwebservice_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the absgenericwebservice patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/gws";;
	*absrestservices_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the absrestservices patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wsr";;
	*AbsUhfMonitor_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the absuhfmonitor patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wum";;
	*absweb_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the absweb patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wpo";;
	*abswebportal_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the abswebportal patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wp2";;
	*absws4mobileapps_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the absws4mobileapps patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/w4m";;
	*webclientx_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
		logline "Unpack the webclientx patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wcl";;
	*webservice2_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web" 
		logline "Unpack the webservice2 patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/ws2";;
	*webclientresidentialdelivery_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web" 
		logline "Unpack the webclientresidentialdelivery patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wrd";;
	*webclientmyuniformassistant_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web" 
		logline "Unpack the webclientmyuniformassistant patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wua";;
	*webclientroutereturns_*.war) 
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web" 
		logline "Unpack the webclientroutereturns patch package $UNATTENDED_FILE."
		unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wrr";;
    *webclientreplacesmartbarcode_*.war)
        [ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
        logline "Unpack the webclientreplacesmartbarcode patch package $UNATTENDED_FILE."
        unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wsb";;
    *mobilerestservices_*.war)
        [ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
        logline "Unpack the absrestservices patch package $UNATTENDED_FILE."
        unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wmr";;
    *absmobilefirebaseservices_*.war)
        [ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web ] && mkdir "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web"
        logline "Unpack the absmobilefirebaseservices patch package $UNATTENDED_FILE."
        unzip -o $UNATTENDED_FILE -d "$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Web/wfb";;

    *) 
		logline "The given file $UNATTENDED_FILE is not a valid ABSSolute patch file."
		unattendedExit;;
	esac
}

unattendedUnpack()
{	
	# Path if a file
	if [ -f $UNATTENDED_PACKAGEPATH ]
	then
		export UNATTENDED_FILE=$UNATTENDED_PACKAGEPATH
		unattendedProcessABSSoluteFile
	fi
	
	# Path is a directory. Find and deploy the highest available patch.
	if [ -d $UNATTENDED_PACKAGEPATH ]
	then
		# Exit when $ABSMENU_FUTURE_ENV_SERVERJAR_VERSION is unavailable
		if [ -z "$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION" ]
		then 
			logline "The version of the future repositoy cannot be found."
			exit 1
		fi
		
		# Distribute highest patch version available to the future repository
		export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "Patch_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.zip" | sort | tail -1)
		if [ ! -z "$UNATTENDED_FILE" ] 
		then 
			unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
		
			# Distribute highest patch version available of the absgenericwebservice to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "absgenericwebservice_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the absrestservices to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "absrestservices_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the AbsUhfMonitor to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "AbsUhfMonitor_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the absweb to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "absweb_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the abswebportal to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "abswebportal_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the absws4mobileapps to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "absws4mobileapps_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
					
			# Distribute highest patch version available of the webclientx to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "webclientx_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the webservice2 to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "webservice2_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the webclientresidentialdelivery to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "webclientresidentialdelivery_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""
			
			# Distribute highest patch version available of the webclientmyuniformassistant to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "webclientmyuniformassistant_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""

			# Distribute highest patch version available of the webclientroutereturns to the future repository
			export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "webclientroutereturns_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
			[ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
			export UNATTENDED_FILE=""

            # Distribute highest patch version available of the webclientreplacesmartbarcode to the future repository
            export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "webclientreplacesmartbarcode_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
            [ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
            export UNATTENDED_FILE=""

            # Distribute highest patch version available of the absmobilefirebaseservices to the future repository
            export UNATTENDED_FILE=$(find $UNATTENDED_PACKAGEPATH -maxdepth 1 -type f -name "absmobilefirebaseservices_$ABSMENU_FUTURE_ENV_SERVERJAR_VERSION*.war" | sort | tail -1)
            [ ! -z "$UNATTENDED_FILE" ] && unattendedProcessABSSoluteFile
            export UNATTENDED_FILE=""
										
		else 
			logline "No patch file for version $ABSMENU_FUTURE_ENV_SERVERJAR_VERSION found in the directory."
		fi
	fi
}

unattendedDeploy()
{
	# Make backup
	unattendedBackup

	# Set glassfish install directory name
	unattendedSetGLASSFISHPATH

	# Update the environment
	if [ ! -z "$ABSMENU_CURRENT_ENV_SERVERJAR_VERSION"  ] && [ ! -z "$ABSMENU_CURRENT_ENV_SERVERJAR_REVISION" ]
	then
		logline "Stopping the environment."
		. $ABSMENUPATH/bin/service_administration.sh stop gf web
	fi
	logline "Update the environment and running SQL scripts."

	export UNATTENDED_SCRIPTRUN="yes"
	. $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" all
	
	if [ $? -ne 0 ] 
	then 
		logline "The deploy process failed. Most likely update/patch SQL scripts failed to execute correctly."
	else
		# Move all sqlscripts to completed directory
		[ ! -d $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts/completed ] && mkdir -p $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts/completed
		mv $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts/*.sql $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts/completed > /dev/null 2>&1
		find $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts -type d -name "_*_sql" -exec mv {} $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/sqlscripts/completed \; > /dev/null 2>&1
	fi
}

unattendedWebDeploy()
{
	# Make backup
	unattendedBackup

	# Set glassfish install directory name
	unattendedSetGLASSFISHPATH

	# Update the environment
	. $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" web webdeploy
	
	if [ $? -ne 0 ] 
	then 
		logline "The web deploy process failed."
	fi
}

unattendedVersion()
{
	# Echo the version of the current repository
	logline "Echo the version details of the environment."
	
	if [ "$ABSMENU_CURRENT_ENV_PATCHSERVERJAR_VERSION" != "-" ]
	then 
		echo $ABSMENU_CURRENT_ENV_PATCHSERVERJAR_VERSION
	else
		echo $ABSMENU_CURRENT_ENV_SERVERJAR_VERSION.$ABSMENU_CURRENT_ENV_SERVERJAR_REVISION
	fi
}

unattendedRestart()
{
	# Restarting the given environment depending on the process value given
	case $UNATTENDED_COMMAND_PROCESS in
	app) 
		logline "Restarting application processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh apprestart;;
	rep) 
		logline "Restarting report processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh represtart;;
	glass) 
		logline "Restarting glassfish processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh webrestart;;
	all) 
		logline "Restarting all processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh restart gf web;;
    *) 
		logline "The given process value is not correct (app/rep/glass/all)"
		unattendedExit;;
	esac
}

unattendedStart()
{
	# Starting the given environment depending on the process value given
	case $UNATTENDED_COMMAND_PROCESS in
	app) 
		logline "Starting application processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh appstart;;
	rep) 
		logline "Starting report processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh repstart;;
	glass) 
		logline "Starting glassfish processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh webstart;;
	all) 
		logline "Starting all processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh start gf web;;
    *) 
		logline "The given process value is not correct (app/rep/glass/all)"
		unattendedExit;;
	esac
}

unattendedStop()
{
	# Stopping the given environment depending on the process value given
	case $UNATTENDED_COMMAND_PROCESS in
	app) 
		logline "Stopping application processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh appstop;;
	rep) 
		logline "Stopping report processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh repstop;;
	glass) 
		logline "Stopping glassfish processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh webstop;;
	all) 
		logline "Stopping all processes from the environment."
		. $ABSMENUPATH/bin/service_administration.sh stop gf web;;
    *) 
		logline "The given process value is not correct (app/rep/glass/all)"
		unattendedExit;;
	esac
}

unattendedReportsUpdate()
{
	# Make a backup
	unattendedBackup
	
	# Push the reports to the environment
	logline "Push the reports to the environment."
    . $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" reports
}

unattendedLicenseUpdate()
{
    # Make a backup
	unattendedBackup
	
	# Push the license to the environment
	logline "Push the license to the environment."
    . $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" license
}

unattendedBackup()
{
	# Make a backup
	logline "Create a backup of the current repository."
	. $ABSMENUPATH/bin/backup_current_environment.sh
}

unattendedPropertiesUpdate()
{
	# Push the propeties to the environment
	logline "Push the properties to the environment."
	. $ABSMENUPATH/bin/generate_properties.sh all normal "$ABSMENU_CURRENT_ENVIRONMENT" x x x x x x x x x x x x x x x x x x x x x x x x x
}

restoreBackup()
{
	# Push the propeties to the environment
	logline "Restore the future repository based on the last backup."
	. $ABSMENUPATH/bin/restore_current_environment.sh
}

unattendedCheckEnvironment()
{
	# Check if the environment exists
	if [ -z "$ABSMENU_CURRENT_ENV_SERVERJAR_VERSION"  ]
	then 
		logline "WARNING: The environment does not seem to exist. The UNATTENDED scriptrun will exit now."
		unattendedExit
	fi
}

unattendedCheckIfNewEnvironment()
{
	# Variables are missing if current repository does not exists
	if [ "$ABSMENU_CURRENT_ENV_SERVERJAR_VERSION" == "-" ]
	then
		export ABSMENU_CURRENT_ENV_SERVERJAR_VERSION="8.03.11.a"
		export ABSMENU_FUTURE_ENV_SERVERJAR_VERSION=`unzip -ca $ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT/Future/Server/Lib/server-impl.jar META-INF/MANIFEST.MF | grep "Name: absgroup/bl/" -A 2 | grep Specification-Version | sed 's/\(.*:\)\(.*\)\(\r\)/\2/' | xargs`
	fi
}

unattendedheapspace()
{
	# Synchronise the heapspace config to the environment
	logline "Synchronising heapspace configuration to the environment."
	. $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" heapspace
	echo
	echo "The heapspace max configuration values are synchronised to all services."
	echo "A restart of the services is required to enable the change."
}

# This function will move abs.sh to all middle-tier servers actively registered in service_registration.cfg
unattendedsyncabsshell()
{
	if [ ! -f "${ABS_ROOTDIR}/abs.sh" ]
	then
		echo "Cannot sync abs.sh because ${ABS_ROOTDIR}/abs.sh does not exists on the server $ABSM_SERVERNAME"
		return 0
	fi
	
	logline "Synchronising absshell configuration to the middle-tier servers."
	
	grep -v '::' $ABSMENUGLOBALCONFIG | awk ' {print $2} ' | sort -u | while read ABSM_SERVERNAME
	do
		rsync -ae "ssh -q" $ABS_ROOTDIR/abs.sh $ABSM_SERVERNAME:/abs
	done

	echo "The ${ABS_ROOTDIR}/abs.sh shell is migrated to all active middle-tier servers in the service_registation.cfg."
}

# Upgrade the service_registation to version 4 format
unattendedupgraderegistration4()
{
	[ $(grep -v '::' $ABSMENUGLOBALCONFIG | grep -v "^$" | head -1 | awk ' {print NF} ') -ne 33 ] && return 0

	[ -f $ABSMENUPATH/config/service_registration.cfg.v4 ] && rm $ABSMENUPATH/config/service_registration.cfg.v4

	awk ' {print gensub (/[^[:blank:]]+/, "X "$15, 15)}' < $ABSMENUPATH/config/service_registration.cfg > $ABSMENUPATH/config/service_registration.cfg.temp
	awk ' {print gensub (/[^[:blank:]]+/, "X "$28, 28)}' < $ABSMENUPATH/config/service_registration.cfg.temp > $ABSMENUPATH/config/service_registration.cfg.v4
	rm $ABSMENUPATH/config/service_registration.cfg.temp
	
	# Save version 3 config
	mv $ABSMENUPATH/config/service_registration.cfg $ABSMENUPATH/config/service_registration.cfg_$(date +"%d-%m-%Y_%H:%M:%S")

	# Rename information section
	sed -i '/::  1_environment           -/c\::  1_environment           - Name of the ABSSolute environment' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  2_servername            -/c\::  2_servername            - servers hostname' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  3_service               -/c\::  3_service               - Not used on Linux. describes the Windows service name of the ABS process' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  4_type                  -/c\::  4_type                  - the type of ABS process instance (app, rep, wpo, wpon, gws, ws2)' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  5_slot                  -/c\::  5_slot                  - instance number (slot) of the ABS process. (formatmask 01, 02, .. 99)' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  6_local_home            -/c\::  6_local_home            - local home path of the ABS process; used for property file generation' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  7_remote_home           -/c\::  7_remote_home           - UNC-path of the ABS process; used for updating software' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  8_user                  -/c\::  8_user                  - web username or Oracle schema name. This is used for property file generation' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/::  9_pwd                   -/c\::  9_pwd                   - web or Oracle schema password. This is used for property file generation' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 10_oratns                -/c\:: 10_oratns                - tnsnames entry (fat) or database SID (rac) to be used for database access; used for property file generation' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 11_orahome               -/c\:: 11_orahome               - Oracle home folder; used for property file generation' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 12_dbservername          -/c\:: 12_dbservername          - Oracle database server DNS name or IP number.' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 13_dbdrivertype          -/c\:: 13_dbdrivertype          - OCI8, thin or rac' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 14_dbportnumber          -/c\:: 14_dbportnumber          - listener port number. standard value is 1521' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 14_dbportnumber          -/a :: 15_heapspace             - The maximal heapspace for appserver/repserver to bypass value from abs.sh' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 15_stationnr             -/c\:: 16_stationnr             - web components stationnumber; used for property file generation' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 16_gfuser                -/c\:: 17_gfuser                - glassfish admin user' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 17_gfpaswrd              -/c\:: 18_gfpaswrd              - glassfish admin password' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 18_domain                -/c\:: 19_domain                - glassfish domain' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 19_webcontext            -/c\:: 20_webcontext            - webcontext of the glassfish deployable module' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 20_webname               -/c\:: 21_webname               - displayname of the glassfish deployable module' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 21_weblib                -/c\:: 22_weblib                - jar to load by the web component before all other jars (i.e. custom skin)' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 22_connappsrv            -/c\:: 23_connappsrv            - the (web) component connects to this appserver machine' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 23_connappslot           -/c\:: 24_connappslot           - the (web) component connects to this appserver slot' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 24_connrepsrv            -/c\:: 25_connrepsrv            - the (web) component connects to this repserver machine' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 25_connrepslot           -/c\:: 26_connrepslot           - the (web) component connects to this repserver slot' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 26_UseNativeFonts        -/c\:: 27_UseNativeFonts        - UseNativeFonts yes or no' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 27_UseNativeFonts        -/a :: 28_ExclCusReport         - Exclude customer reports from synchronising, enable with true' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 27_GF_version            -/c\:: 29_GF_version            - Glassfish version (301, 312, 4 or 411)' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 28_client_distrib_server -/c\:: 30_client_distrib_server - client distribution server' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 29_client_distrib_dir    -/c\:: 31_client_distrib_dir    - client distribution home directory' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 30_user2                 -/c\:: 32_user2                 - web username for mobile app service, used for garment assistant' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 31_pwd2                  -/c\:: 33_pwd2                  - web password for mobile app service, used for garment assistant' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 32_stationnr2            -/c\:: 34_stationnr2            - web stationnumber for mobile app service, used for garment assistant' $ABSMENUPATH/config/service_registration.cfg.v4
	sed -i '/:: 33_inet_key              -/c\:: 35_inet_key              - i-net license key for the report server; used for property file generation' $ABSMENUPATH/config/service_registration.cfg.v4

	# Rename column headers
	LINENUMBER=$(grep -n '::1_environment[[:blank:]]*2_servername*' $ABSMENUPATH/config/service_registration.cfg.v4 | cut -d ':' -f1)
	cat $ABSMENUPATH/config/service_registration.cfg.v4 | awk -v var="$LINENUMBER" ' NR<var { print $0 } '  > $ABSMENUPATH/config/service_registration.cfg
	echo -n :: >>$ABSMENUPATH/config/service_registration.cfg
	grep -Eo '::[[:blank:]]{1,2}[[:digit:]]{1,2}_[a-zA-Z0-9_]*' $ABSMENUPATH/config/service_registration.cfg.v4 | awk 'BEGIN { ORS=" " }; { print $2 }' >> $ABSMENUPATH/config/service_registration.cfg
	echo >> $ABSMENUPATH/config/service_registration.cfg
	cat $ABSMENUPATH/config/service_registration.cfg.v4 | awk -v var="$LINENUMBER" ' NR>var { print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35 } ' | column -t -s ' ' >> $ABSMENUPATH/config/service_registration.cfg

	# Remove v4 temp config
	rm $ABSMENUPATH/config/service_registration.cfg.v4
	
	# Beautify the service_registation file
	unattendedbeautifyregistration true
	
	# Response to user
	echo "The service_registration.cfg file is altered."
	echo "It is recommended to validate the config after"
}

# Beautify the service_registation file
unattendedbeautifyregistration()
{
	[ -z "$1" ] && cp $ABSMENUPATH/config/service_registration.cfg $ABSMENUPATH/config/service_registration.cfg_$(date +"%d-%m-%Y_%H:%M:%S")
	mv $ABSMENUPATH/config/service_registration.cfg $ABSMENUPATH/config/service_registration.cfg.temp
	
	LINENUMBER=$(grep -n '::1_environment[[:blank:]]*2_servername*' $ABSMENUPATH/config/service_registration.cfg.temp | cut -d ':' -f1)
	cat $ABSMENUPATH/config/service_registration.cfg.temp | awk -v var="$LINENUMBER" ' NR<var { print $0 } '  > $ABSMENUPATH/config/service_registration.cfg
	cat $ABSMENUPATH/config/service_registration.cfg.temp | awk -v var="$LINENUMBER" ' NR>=var { print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35 } ' | column -t -s ' ' >> $ABSMENUPATH/config/service_registration.cfg
	rm $ABSMENUPATH/config/service_registration.cfg.temp
}


#### Main      ####################################################################

# Select environment properties
export UNATTENDED_ENABLED="yes"
. $ABSMENUPATH/bin/select_current_evironment.sh select $UNATTENDED_ENVIRONMENT  2>&1 >/dev/null

# Case on the UNATTENDED_COMMAND variable
case $UNATTENDED_COMMAND in
	start) 
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED START"
		unattendedStart;;
	stop)
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED STOP"
		unattendedStop;;
	restart) 
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED RESTART"
		unattendedRestart;;
	unpack) 
		logline "COMMAND - UNATTENDED UNPACK"
		unattendedCheckIfNewEnvironment
		unattendedUnpack;;
	deploy) 
		logline "COMMAND - UNATTENDED DEPLOY"
		unattendedCheckIfNewEnvironment
		unattendedDeploy;;
	webdeploy) 
		logline "COMMAND - UNATTENDED WEBDEPLOY"
		unattendedCheckIfNewEnvironment
		unattendedWebDeploy;;
	reports) 
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED REPORTS"
		unattendedReportsUpdate;;
	license) 
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED LICENSE"
		unattendedLicenseUpdate;;
	heapspace) 
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED HEAPSPACE"
		unattendedheapspace;;
	syncabsshell) 
		logline "COMMAND - UNATTENDED SYNCABSSHELL"
		unattendedsyncabsshell;;
	backup)
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED BACKUP"
		unattendedBackup;;
	restore)
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED RESTORE"
		restoreBackup;;
	properties)
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED PROPERTIES"
		unattendedPropertiesUpdate;;
	version)
		unattendedCheckEnvironment
		logline "COMMAND - UNATTENDED VERSION"
		unattendedVersion;;
	upgraderegistration4)
		logline "COMMAND - UNATTENDED UPGRADEREGISTRATION4"
		unattendedupgraderegistration4;;
	beautifyregistration)
		logline "COMMAND - UNATTENDED BEAUTIFYREGISTRATION"
		unattendedbeautifyregistration;;
    *) 
		echo "The Command value given does not exists";;
esac
