#!/bin/bash
#
#########################################################################################
# Script: 		absmenu.sh
# Description: 	Manage ABSSolute software deployment 
# Author: 		ABS Laundry Business Solutions
# Version: 		4.6
#### Changelog of script ################################################################
# Date        Author    Version 	Change    
# 15-May-2011 JMI		1.0			Initial version
# 29-May-2011 JMI		1.2			Moved config file to absmenu/config/absmenu_config.sh
# 26-Sep-2015 ROP		1.3			Merged some scripts
# 19-May-2015 ROP		1.6			Added android service
# 14-Aug-2015 ROP		1.7			Added rolling update mechanism
# 30-Jan-2017 MBU		2.2			Uploaded latest used version from VM-ASP-TST to SVN
# 31-Jan-2017 MBU		2.3			Development unattended auto deploy options for VM-ASP-TST EU_LATEST/US_LATEST
# 08-Feb-2017 AFA		2.4			Application Server License deployment / Reports deployment / I-Net License Updated
# 25-Jan-2018 IGH		2.5			Change of webcomponents naming as per 3-letter naming convention
# 12-Sep-2018 MBU		2.6			Extention of UNATTENDED ABSMENU usage
# 28-Sep-2018 MBU		2.7			Extention of UNATTENDED ABSMENU usage
# 05-Nov-2018 MBU		2.8			Extention of UNATTENDED ABSMENU usage
# 06-Nov-2018 MBU		2.9			Added sqlscript log based error detection for UNATTENDED ABSMENU usage
# 27-Dec-2018 MBU		3.0			Added pre patchrun check
#									Added support for ABSSolute releases from GIT
#									Added parallel webserver deployment
#									Remove rolling patching mechanism
#									Added SNMP check during glassfish startup
# 07-Jan-2018 MBU		3.1			Bugfix: exit code is always 1 during unattended deployment actions
# 07-Feb-2019 MBU		3.2			Bugfix: Unpack patch 9.03.00.RELEASE.px deletes future repository
# 26-Mar-2019 IGH/MBU	3.3			Added support to deploy new webapplications: wua=webclient my uniform assistant wrd=webclient residential delivery wrr=webclient route returns
#			  						Bugfix: Install glassfish on non web servers
# 04-Apr-2019 MBU		4.0			Added generation of RMIDIAGNOSTICPORT in absserver.properties
#									Added property generation of rac connection
#									Added exclusion option for CUSTOMER reports with ABSM_EXCLUDECUSTREP setting
#									Added custom heapspace setting for app/rep services
#									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
#									Added execution of conversion scripts after upgrade
# 17-Apr-2019 MBU		4.1			Support for report server only slots
#									Default t flag value (all) on start/stop/restart CLI usage
# 07-May-2019 MBU		4.2			Bugfix: Parallel deploy custom skin for WP2 gives deployment error
# 27-Jun-2019 MBU		4.3			Bugfix: Service retrieval on partial environment name hit
# 15-Jul-2019 MBU		4.4			Bugfix: Custom config settings not working (bug originated from version 4.3)
# 21-Oct-2019 MBU		4.5			Bugfix: Auto deploy feature not working with SNMP selftest value in ABSSolute 9.03.04 (switch to SNMP status value)
#
#
# 4.6   CHECK BITBUCKET LOG FOR HISTORY CHANGES
# 
#    DO NOT ADD HISTORY CHANGES ANYMORE
#########################################################################################

#### settings / parameters / variables / etc ############################################
SCRIPTRELEASE="4.6"             # script version
SCRIPTDATE="21102019"           # date of last change to script (ddmmyy)
SCRIPTUSER=$(whoami)            # user that started the script. 

#### Internal variables /parameters -- DO NOT CHANGE ####################################
LOGDATE=$(date +%Y_%V*)
SCRIPTVERSION="$SCRIPTRELEASE"_"$SCRIPTDATE"
TERM=linux

## Set environment using the absmenu_config script ######################################
if [ -x ./absmenu/config/absmenu_config.sh ]
then
    . ./absmenu/config/absmenu_config.sh
else
    if [ -x /abs/absmenu/config/absmenu_config.sh ]
    then
        . /abs/absmenu/config/absmenu_config.sh
    else
        echo "ABS menu script - settings not found !  Please check..."
        echo "Aborting..."
        echo 
        exit 1
    fi
fi

# check if the needed local directories and files exist
if [ ! -d "$ABSMENUPATH" ]
then
	echo "Directory $ABSMENUPATH does not exist !"
	echo "Please check..." 
	exit 1
fi
if [ ! -e "$ABSMENUGLOBALCONFIG" ]
then
	echo "Configuration file $ABSMENUGLOBALCONFIG does not exist !"
	echo "Please check..." 
	exit 1
fi

DOABSLOGGING="yes"
if [ ! -d "$ABSMENULOGPATH" ]
then
    mkdir "$ABSMENULOGPATH"
    [ ! -d "$ABSMENULOGPATH" ] && DOABSLOGGING="no"
fi
export DOABSLOGGING

#########################################################################################
# menu options and functions 
# The function names are also used to build the on-screen menu.
#########################################################################################

# Check SNMP status code. Return SNMP status
snmpcheck_app_server()
{
	# $1 = SNMP_SERVER
	# $2 = SNMP_SLOT

	SNMP_SERVER=$1
	SNMP_SLOT=$2
	
	[ ${#SNMP_SLOT} == 1 ] && SNMPVALUE=$(snmpwalk -c public -v 1 udp:$SNMP_SERVER:50${SNMP_SLOT}14 1.3.6.1.4.1.227.1.1 | rev | head -c2 | rev | xargs)
	[ ${#SNMP_SLOT} == 2 ] && SNMPVALUE=$(snmpwalk -c public -v 1 udp:$SNMP_SERVER:5${SNMP_SLOT}14 1.3.6.1.4.1.227.1.1 | rev | head -c2 | rev | xargs)
	
	[ "$SNMPVALUE" == "1" ] && return 0
	return 1
}

absmenu_log()
{
    # first set variable ABSMESSAGE to a text you want to log
    # then call absmenu_log to timestamp it and write it to the logfile
    if [ "$DOABSLOGGING" == "yes" ]
    then
        echo -n $(date +%T) >> $ABSMSCRIPTLOGNAME
        echo "  $ABSMESSAGE" >> $ABSMSCRIPTLOGNAME
    fi
}

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

deploy_future_to_environment()
{
    # $1 - all / srv / web
    [ "$1" != "webapps" ] && . $ABSMENUPATH/bin/service_administration.sh stop gf web
    . $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" "$1"
}

touch $ABSMSCRIPTLOGNAME
echo >> $ABSMSCRIPTLOGNAME
echo "-------------------------------------------------------------------------------" >> $ABSMSCRIPTLOGNAME
echo >> $ABSMSCRIPTLOGNAME

export ABSMESSAGE="User $(whoami) started $0 on $(date +%d-%b-%Y)"
absmenu_log

selectoptions_s() # Software update (complete)
{
    export ABSMESSAGE="MENUACTION: s - automatic update (backup, stop, distribute, start)"
    absmenu_log
    [ $FIRSTRUNDONE == N -a "$ABSM_DOAUTOBACKUP" == Y ] && . $ABSMENUPATH/bin/backup_current_environment.sh
    case $UPDATEWHAT in
        a|A)    deploy_future_to_environment all;;
        s|S)    deploy_future_to_environment srv;;
        w|W)    deploy_future_to_environment webapps;;
    esac
    export FIRSTRUNDONE=Y
}

selectoptions_r() # Reports update 
{
    export ABSMESSAGE="MENUACTION: r - automatic reports update (backup, copy reports + fonts)"
    absmenu_log
    [ $FIRSTRUNDONE == N -a "$ABSM_DOAUTOBACKUP" == Y ] && . $ABSMENUPATH/bin/backup_current_environment.sh
    . $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" reports
    export FIRSTRUNDONE=Y
}  

selectoptions_l() # License update 
{
    export ABSMESSAGE="MENUACTION: k - license update"
    absmenu_log
    [ $FIRSTRUNDONE == N -a "$ABSM_DOAUTOBACKUP" == Y ] && . $ABSMENUPATH/bin/backup_current_environment.sh
    # Do not restart any service -- . $ABSMENUPATH/bin/service_administration.sh stop gf web
    . $ABSMENUPATH/bin/service_binrep_update.sh "$ABSMENU_CURRENT_ENVIRONMENT" license
    # Do not restart any service -- . $ABSMENUPATH/bin/service_administration.sh start gf web
    export FIRSTRUNDONE=Y
}  

selectoptions_p() # Generate property files
{
    export ABSMESSAGE="MENUACTION: 8 - Generate properties and xml files"
    absmenu_log
    if [ $FIRSTRUNDONE == N ]
    then
        export RESTORE_YN=N
        echo
        read -p "Are you SURE you want to re-generate properties and xml files for the $ABSMENU_CURRENT_ENVIRONMENT environment? (Y/N)  " RESTYN
        export ABSMESSAGE="response to \"are you sure\" = $RESTYN"
        absmenu_log
        export RESTYN
    fi
    [ "$RESTYN" == Y -o "$RESTYN" == y ] && . $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
    export FIRSTRUNDONE=Y
}

selectoptions_h() # Maximal heapspace sync
{
    export ABSMESSAGE="MENUACTION: h - heapspace max sync"
    absmenu_log
    . $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."
	export FIRSTRUNDONE=Y
} 

selectoptions_() #
{
    echo
}

selectoptions_1() # Start environment
{
    export ABSMESSAGE="MENUACTION: 1 - Start environment"
    absmenu_log
    . $ABSMENUPATH/bin/service_administration.sh start gf web
}

selectoptions_2() # Stop environment
{
    export ABSMESSAGE="MENUACTION: 2 - Stop environment"
    absmenu_log
    . $ABSMENUPATH/bin/service_administration.sh stop gf $DOALSOWEB
}

selectoptions_3() # Restart environment
{
    export ABSMESSAGE="MENUACTION: 3 - Restart environment"
    absmenu_log
    . $ABSMENUPATH/bin/service_administration.sh restart gf web
}

selectoptions_4() # List registered server components
{
    export ABSMESSAGE="MENUACTION: l - list registred server components"
    absmenu_log
    . $ABSMENUPATH/bin/service_administration.sh list web
}

selectoptions_5() # Backup software (current environment)
{
    export ABSMESSAGE="MENUACTION: 4 - Backup environment"
    absmenu_log
    . $ABSMENUPATH/bin/backup_current_environment.sh
}

selectoptions_6() # Restore last backup
{
    export ABSMESSAGE="MENUACTION: 5 - Restore last environment backup"
    absmenu_log
    if [ $FIRSTRUNDONE == N ]
    then
        RESTORE_YN=N
        echo
        read -p "Are you SURE you want to restore environment $ABSMENU_CURRENT_ENVIRONMENT to the last backed up situation? (Y/N)  " RESTORE_YN
        export ABSMESSAGE="response to \"are you sure\" = $RESTORE_YN"
        absmenu_log
        export RESTORE_YN=N
    fi
    
    if [ "$RESTORE_YN" == "Y" -o "$RESTORE_YN" == "y" ] 
    then 
        . $ABSMENUPATH/bin/restore_current_environment.sh
        deploy_future_to_environment all
        export ABSMESSAGE="Backup restored to future repository and distributed to server(s)"
        absmenu_log
    fi
    export FIRSTRUNDONE=Y
}

selectoptions_() #
{ 
    echo
}

selectoptions_m() # Environment selection menu
{
    export ABSMESSAGE="MENUACTION: m - select new environment"
    absmenu_log
    . $ABSMENUPATH/bin/select_current_evironment.sh normal
}

selectoptions_q() # Quit
{
    exit
}

# Function to check the column count in service_registration.cfg. Will exits when it is incorrect
check_service_registration()
{
	if [ $(grep -v '::' $ABSMENUGLOBALCONFIG  | grep -v "^$" | head -1 | awk ' {print NF} ') -ne 35 ] 
	then
		echo "Please check the presents of columns: 15_heapspace and 28_ExclCusReport"
		echo "'/abs/absmenu.sh -c upgraderegistration4' can be used to add the columns. It is recommended to validate after."
		exit 0
	fi 
}

############### main body ##############################
clear			

# Check flags for unattended deployment
while getopts c:e:f:t: OPT 
do
	case "$OPT" in
	c)  export UNATTENDED_COMMAND=$( echo "$OPTARG" | tr '[:upper:]' '[:lower:]');;					#Command for unattended option
	e)  export UNATTENDED_ENVIRONMENT=$OPTARG;;														#Environment for unattended command
    f)  export UNATTENDED_PACKAGEPATH=$OPTARG;;														#Optional patch/update package or directory
	t)  export UNATTENDED_COMMAND_PROCESS=$( echo "$OPTARG" | tr '[:upper:]' '[:lower:]');;			#Mandatory with c flag when start/stop/restart (app/rep/web/all)
    esac
done

# Run abs.sh sync or registration update
if [ "$UNATTENDED_COMMAND" == "syncabsshell" ] || [ "$UNATTENDED_COMMAND" == "upgraderegistration4" ] || [ "$UNATTENDED_COMMAND" == "beautifyregistration" ]
then
	. $ABSMENUPATH/bin/unattended_deploy.sh
	exit $?
fi

# Validate the column count in the config
check_service_registration

# Enable unattended deployment when c and e flags are given
if [ ! -z "$UNATTENDED_COMMAND"  ] && [ ! -z "$UNATTENDED_ENVIRONMENT"  ]
then
	[ -z "$UNATTENDED_COMMAND_PROCESS" ] && export UNATTENDED_COMMAND_PROCESS="all"
	. $ABSMENUPATH/bin/unattended_deploy.sh
	exit $?
fi

# Select environment for further processing
export ABSMESSAGE="Select new environment (initial)"
absmenu_log

. $ABSMENUPATH/bin/select_current_evironment.sh normal

# set correct glassfish path component
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


while :
do
	clear
	# Display details on the selected environment
	echo "Customer / Environment : $ABSMENU_CURRENT_ENV_LICCODE / $ABSMENU_SELECTED_ENVIRONMENT"
	echo "Current Server version : $ABSMENU_CURRENT_ENV_SERVERJAR_VERSION $ABSMENU_CURRENT_ENV_SERVERJAR_BUILDTIME $ABSMENU_CURRENT_ENV_SERVERJAR_REVISION"
	echo "Current Patch version  : $ABSMENU_CURRENT_ENV_PATCHSERVERJAR_VERSION $ABSMENU_CURRENT_ENV_PATCHSERVERJAR_BUILDTIME $ABSMENU_CURRENT_ENV_PATCHSERVERJAR_REVISION"
	echo "Future Server version  : $ABSMENU_FUTURE_ENV_SERVERJAR_VERSION $ABSMENU_FUTURE_ENV_SERVERJAR_BUILDTIME $ABSMENU_FUTURE_ENV_SERVERJAR_REVISION"
	echo "Future Patch version   : $ABSMENU_FUTURE_ENV_PATCHSERVERJAR_VERSION $ABSMENU_FUTURE_ENV_PATCHSERVERJAR_BUILDTIME $ABSMENU_FUTURE_ENV_PATCHSERVERJAR_REVISION"
	echo "Repository home        : $ABSMENUREPOSITORYSERVER:$ABSMENUREPOSITORYLOCATION/$ABSMENU_CURRENT_ENVIRONMENT"
	echo "Backup home            : $ABSMENUBACKUPSERVER:$ABSMENUBACKUPLOCATION/$ABSMENU_CURRENT_ENVIRONMENT"
	echo

	# select a menu option
    echo = Menu =================================================
    echo 
    grep selectoptions_ absmenu.sh | grep -v V_MENU_CHOICE | sed -e "s/\(selectoptions_\)\(.*\)\(() #\)\(.*\)/\2 \4/"
    echo
    read -p "Make a choice or press ENTER to quit: " V_MENU_CHOICE
    echo
	
    if [ "$V_MENU_CHOICE" == "q" -o "$V_MENU_CHOICE" == "Q" -o ! "$V_MENU_CHOICE" ] 
    then 
        export ABSMESSAGE="Exit script"
        absmenu_log
        echo
        echo "Terminating script..."
        echo
        break
    fi
	
	case "$V_MENU_CHOICE" in
        1|2|3|4|5|6|l|m|p|q|r|s|h)  MENU_PARAM_OK=Y;;
        *)                          MENU_PARAM_OK=N;;
    esac
    if [ "$MENU_PARAM_OK" == "N" ]
	then
		echo Unknown menu option \""$V_MENU_CHOICE"\". Please select again.
	else
        export FIRSTRUNDONE=N
        export SCRIPTQUESTIONDONE=N
        export DOALSOWEB=web
        if [ "$V_MENU_CHOICE" == "s" ]
        then
            read -p "[a] - update all (default)   [s] - app/rep only   [w] - web only  " UPDATEWHAT
            export ABSMESSAGE="response to \"app_rep\web\all\" = $UPDATEWHAT"; absmenu_log
            echo ""
            case $UPDATEWHAT in
                a|A|s|S|w|W)    ;;
                *)              UPDATEWHAT=a;;
            esac
            export UPDATEWHAT
            case $UPDATEWHAT in
                a|A)    echo "Update application and report server(s) and web components";;
                s|S)    echo "Update application and report server(s) only";;
                w|W)    echo "Update web components only";;
            esac
            echo ""
        fi
		export ABSMENU_CURRENT_ENVIRONMENT="$ABSM_ENVIRONMENT_NAME"
		selectoptions_$V_MENU_CHOICE
	fi
    echo
    read -p "Press ENTER to continue " V_MENU_CHOICE
    export ABSMENU_CURRENT_ENVIRONMENT="$ABSM_ENVIRONMENT_NAME"
    . $ABSMENUPATH/bin/select_current_evironment.sh get_details
done
