#!/bin/sh
#
# $Id$ Copyright (c) 2025 EMC Corporation.
#
#
# Copyright (c) 2025 EMC Corporation.
#
# All rights reserved.  This is an UNPUBLISHED work, and
# comprises proprietary and confidential information of EMC.ht
# Unauthorized use, disclosure, and distribution are strictly
# prohibited.  Use, duplication, or disclosure of the software
# and documentation by the U.S. Government is subject to
# restrictions set forth in a license agreement between the
# Government and EMC or other written agreement specifying
# the Government's rights to use the software and any applicable
# FAR provisions, such as FAR 52.227-19.
#

#
# Function:
#   valid_user_group
#
# Description:
#   Checks if the given user and group is valid
#   and if the user is member of that group.
#
# Arguments:
#
#	Parameter			Purpose
#   ----------------------  --------------------------------------------
#	$1			User name.
#	$2			Group name.
#
# Returns:
#
#	Return Variable		    Purpose
#   ----------------------  --------------------------------------------
#	    result		valid or the error.
#
valid_user_group()
{
    USERID=`cat /etc/passwd | grep "^$1:" | cut -d ":" -f 3`
    if [ "X$USERID" != "X" ] ; then
        expr $USERID + 1 > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        if [ $USERID -lt 0 ] ; then
			validuserid=false
        else
			validuserid=true
        fi
    else
        validuserid=false
    fi
    else
    validuserid=false
    fi
    if [ "X$2" != "X" ] ; then
		PRIMARYGRPID=`cat /etc/passwd | grep "^$1:" | cut -d ":" -f 4`
    if [ "$validuserid" = "true" -a  "X$PRIMARYGRPID" != "X" ] ; then
        GROUPID=`cat /etc/group | grep "^$2:" | cut -d ":" -f 3`
        GROUPMEMBERS=`cat /etc/group | grep "^$2:" | cut -d ":" -f 4`
        if [ "X$GROUPID" != "X" ] ; then
	if [ "$PRIMARYGRPID" = "$GROUPID" ] ; then
	    result="valid";
	else
	    if [ "X$GROUPMEMBERS" != "X" ] ; then
	    PRESENT=`echo "$GROUPMEMBERS" | grep "$1"`
	    if [ -n "$PRESENT" ] ; then
	        result="valid"
	    else
	        result="no_membership"
	    fi
	    else
		result="no_membership"
	    fi
	fi
        else
	    result="no_group"
        fi
    else
        result="no_user"
    fi
    else
	#No group check requested
	if [ "$validuserid" = "true" ] ; then
	    result="valid"
	fi
    fi
}

#
# Function:
#   readexistingconfig
#
# Description:
#   Checks presence of old config file and reads its values
#
# Arguments:
#
#   Parameter	    Purpose
#   ----------------------  --------------------------------------------
#
# Returns:
#
#   Return Variable	Purpose
#   ----------------------  --------------------------------------------
#   OLDCONF
#   OLDCONFVER
#   DEFAULT_BASEPORT
#   DEFAULT_GSTPORT
#   DEFAULT_DBSRVPORT
#   DEFAULT_DBUSER
#   DEFAULT_AUTHHOST
#   DEFAULT_AUTHPORT
#   DEFAULT_DBDIR
#
readexistingconfig()
{
    gstdconf="Success"
    httpdconf="Success"

    if [ "$1" = "console" ]; then
	echo "[1]: Reading config files for getting the existing configuration..."
    else
	echo "[1]: Reading config files for getting the existing configuration..." >> "$instlog"
    fi
    # Check if an old config file is present
    if [ -d ${base}/etc ]; then
	CONFFILES=`ls -lat ${base}/etc | grep "\.gstd.conf"`
    fi

    if [ -n "$CONFFILES" ]; then
	OLDCONF=`ls -lt ${base}/etc/.gstd.conf* | awk 'NR == 1 { print $NF }'`
	# Get the version of the old Console installation
	# Get the last component of the file name
	OLDCONFVER=`echo $OLDCONF | awk -F/ 'NR == 1 { print $NF }'`
	#Get the version
	OLDCONFVER=`echo $OLDCONFVER | cut -d "." -f 4,5 | sed 's?[^0-9]??g'`

	# if there is .gstd.conf left behind by the %pre script, then it takes precedence
	if [ -f ${base}/etc/.gstd.conf.latest ]; then
	    OLDCONF="${base}/etc/.gstd.conf.latest"
	fi

	if [ -f "$OLDCONF" ]; then
	    DEFAULT_BASEPORT=`awk '/http_svc_port/ { print substr($4,1,length($4)-1) }' "$OLDCONF"`
	    DEFAULT_GSTPORT=`awk '/clnt_svc_port/ { print substr($4,1,length($4)-1) }' "$OLDCONF"`
	    DEFAULT_DBSRVPORT=`awk '/db_svc_port/ { print substr($4,1,length($4)-1) }' "$OLDCONF"`
	    DEFAULT_DBUSER=`awk '/gst_postgres_user/ { print substr($4,2,length($4)-3) }' "$OLDCONF"`
	    DEFAULT_AUTHHOST=`awk '/authsvc_hostname/ { print substr($4,2,length($4)-3) }' "$OLDCONF"`
	    DEFAULT_AUTHPORT=`awk '/authsvc_port/ { print substr($4,1,length($4)-1) }' "$OLDCONF"`
	    DEFAULT_DBDIR=`awk '/current_db_dir/ {
				DBNM = $4
				i = 5
				while ( i <= NF ) {
					DBNM = DBNM " " $i
					++i
				}
			}
			END {
				print substr(DBNM,2,length(DBNM)-3)
			}' "$OLDCONF"`
	else
	    gstdconf="Failed"
	fi
    else
	gstdconf="Failed"
    fi

    #httpd.conf file read
    $gstconfig -r >> "$instlog" 2>&1
    if [ $? -ne 0 ]; then
	if [ "$1" = "console" ]; then
	    echo "Cannot read the httpd.conf file."
	else
	    echo "Cannot read the httpd.conf file." >> "$instlog"
	fi
	httpdconf="Failed"
    fi

    if [ -f $httpsconfig ]; then
	install_type=$(grep INSTALLATION_TYPE $httpsconfig | cut -d' ' -f2)
	cert_file=$(grep SSLCertificatefile $httpsconfig | cut -d' ' -f2)
	key_file=$(grep SSLCertificateKeyfile $httpsconfig | cut -d' ' -f2)
    fi

    if [[ "$gstdconf" == "Success" && "$httpdconf" == "Success" ]]; then
	if [ "$1" = "console" ]; then
                echo "Successfully read existing configuration."
	else
                echo "Successfully read existing configuration." >> "$instlog"
        fi
    else
	if [ "$1" = "console" ]; then
            echo "Failed to read existing configuration."
            echo
        else
            echo "Failed to read existing configuration." >> "$instlog"
        fi
        exit 1
    fi
}

#
# Function:
#   validateconfig
#
# Description:
#   Validates each value read by readexistingconfig function and checks whether
#	values are right fit for upgrades.
#
# Arguments:
#
#   Parameter					Purpose
#   ----------------------  --------------------------------------------
#
# Returns:
#
#   Return Variable					Purpose
#   ----------------------  --------------------------------------------
#	result						true, if values can be reused
#								false, if values are incomplete or cant be reused.
#
validateconfig()
{
    retain="Success"

    #Validate each parameter
    retained_status=('Version1.0')
    err_str=('Version1.0')

    if [ "$1" = "console" ]; then
	echo "[2]: Validating existing configuration..."
    else
	echo "[2]: Validating existing configuration..." >> "$instlog"
    fi

    #DEFAULT_BASEPORT#
    if [ "X$DEFAULT_BASEPORT" = "X" ]; then
	retained_status+=("No")
	err_str+=("No details for WebServer Port present in config files.")
	retain="Failed"
    else
	if validport $DEFAULT_BASEPORT ; then
	    retained_status+=("Yes")
	    err_str+=("$DEFAULT_BASEPORT")
	else
	    retained_status+=("No")
	    err_str+=("$validporterrstr")
	    retain="Failed"
	fi
    fi

    #DEFAULT_GSTPORT#
    if [ "X$DEFAULT_GSTPORT" = "X" ]; then
	retained_status+=("No")
	err_str+=("No details for GST Server Port present in config files.")
	retain="Failed"
    else
	#In the rare case, upgrade was done before nmc_config was run, reset GSTPORT
	if [ -n "$DEFAULT_GSTPORT" -a "$DEFAULT_GSTPORT" = "1970" ]; then
	    retained_status+=("No")
	    err_str+=("nmc_config is not run for last installed version.")
	else
	    if validport $DEFAULT_GSTPORT; then
		retained_status+=("Yes")
		err_str+=("$DEFAULT_GSTPORT")
	    else
		retained_status+=("No")
		err_str+=("$validporterrstr")
		retain="Failed"
	    fi
	fi
    fi

    #DEFAULT_DBSRVPORT#
    if [ "X$DEFAULT_DBSRVPORT" = "X" ]; then
	retained_status+=("No")
	err_str+=("No details for DB Port present in config files.")
	retain="Failed"
    else
	if [ $DEFAULT_DBSRVPORT -eq $DEFAULT_BASEPORT ] ; then
	    retained_status+=("No")
	    err_str+=("Web server and database server port numbers cannot be the same.")
	elif [ $DEFAULT_DBSRVPORT -eq $DEFAULT_GSTPORT ] ; then
	    retained_status+=("No")
	    err_str+=("GST server and database server port numbers cannot be the same.")
	else
	    if validport $DEFAULT_DBSRVPORT; then
		retained_status+=("Yes")
		err_str+=("$DEFAULT_DBSRVPORT")
	    else
		retained_status+=("No")
		err_str+=("$validporterrstr")
		retain="Failed"
	    fi
	fi
    fi

    #DEFAULT_DBDIR#
    if [ "X$DEFAULT_DBDIR" = "X" ]; then
	retained_status+=("No")
	err_str+=("No details for DB directory present in config files.")
	retain="Failed"
    else
	# For upgrades, do not use old db path if the old version was sybase db
	if [ -f "$DEFAULT_DBDIR/lgto_gst.db" ]; then
	    DEFAULT_DBDIR="/nsr/nmc/nmcdb"
        fi
	if [ ! -d "$DEFAULT_DBDIR/$DBNAME" ]; then
	    retained_status+=("No")
	    err_str+=("Database directory empty. No existing database present.")
	    retain="Failed"
	else
	    is_ascii_path "$DEFAULT_DBDIR"
	    if [ "$result" = "n" ]; then
		retained_status+=("No")
		err_str+=("The path contains invalid characters: $result_temp_path")
		retain="Failed"
	    else
		retained_status+=("Yes")
		err_str+=("$DEFAULT_DBDIR")
	    fi
	fi
    fi

    #DEFAULT_AUTHHOST/DEFAULT_AUTHPORT#
    if [ "X$DEFAULT_AUTHHOST" = "X" ]; then
	authhost="missing"
    else
	authhost="available"
    fi
    if [ "X$DEFAULT_AUTHPORT" = "X" ]; then
	authport="missing"
    else
	authport="available"
    fi
    
    #Authc Host & Authc Port
    if [[ ("$authhost" = "available") && ("$authport" = "available") ]]; then
	SHORTCURHOST=`hostname | cut -d "." -f 1`
	SHORTAUTHCHOST=`echo $DEFAULT_AUTHHOST | cut -d "." -f 1`
	if [ ! -z "$SHORTCURHOST" -a ! -z "$SHORTAUTHCHOST" ]; then
	    if [ "$SHORTCURHOST" = "$SHORTAUTHCHOST" -o "$SHORTAUTHCHOST" = "localhost" ]; then
		retained_status+=("Yes")
		err_str+=("$DEFAULT_AUTHHOST")
		retained_status+=("Yes")
		err_str+=("$DEFAULT_AUTHPORT")
	    else
		"$gstauthcfg" -h "$DEFAULT_AUTHHOST" -p "$DEFAULT_AUTHPORT" -t  >> "$instlog" 2>&1
		if [ $? -ne 0 ] ; then
		    retained_status+=("No")
		    err_str+=("Unable to contact authc on host $DEFAULT_AUTHHOST and port $DEFAULT_AUTHPORT")
		    retained_status+=("No")
		    err_str+=("Unable to contact authc on host $DEFAULT_AUTHHOST and port $DEFAULT_AUTHPORT")
		    retain="Failed"
		else
		    retained_status+=("Yes")
		    err_str+=("$DEFAULT_AUTHHOST")
		    retained_status+=("Yes")
		    err_str+=("$DEFAULT_AUTHPORT")
		fi
	    fi
	fi
    elif [[ ("$authhost" = "missing") && ("$authport" = "available") ]]; then
	retained_status+=("No")
        err_str+=("No details for AUTHC Host present in config files.")
	retained_status+=("Yes")
	err_str+=("$DEFAULT_AUTHPORT")
        retain="Failed"
    elif [[ ("$authhost" = "available") && ("$authport" = "missing") ]]; then
	retained_status+=("Yes")
        err_str+=("$DEFAULT_AUTHHOST")
	retained_status+=("No")
        err_str+=("No details for AUTHC Port present in config files.")
        retain="Failed"
    elif [[ ("$authhost" = "missing") && ("$authport" = "missing") ]]; then
	retained_status+=("No")
        err_str+=("No details for AUTHC Host present in config files.")
	retained_status+=("No")
        err_str+=("No details for AUTHC Port present in config files.")	
        retain="Failed"
    fi

    #Apache httpd certificate and key file
    valid_cert="false"
    if [[ ($cert_file != /*) && ($key_file != /*) ]]; then
        cert_file=${base}/apache/`sed -e 's/"//g' <<< $cert_file`
        key_file=${base}/apache/`sed -e 's/"//g' <<< $key_file`
    fi

    if [[ ($install_type -eq 2) ]]; then
	use_exist_cert="true"
	if [[ (-f $cert_file) && (-f $key_file) ]]; then
	    validatecert
	    if [ $error_number -eq 0 ]; then
		retained_status+=("Valid")
		err_str+=("$cert_file")
		retained_status+=("Valid")
		err_str+=("$key_file")
	    else
		retain="Failed"
		if [[ ("$usecert" = "no") && ("$usekey" = "no") ]]; then
		    retained_status+=("Not Valid")
		    retained_status+=("Not Valid")
		    err_str+=("No read permissions.")
		    err_str+=("No read permissions.")
		elif [ "$usecert" = "no" ]; then
		    retained_status+=("Not Valid")
		    retained_status+=("Valid")
		    err_str+=("No read permissions.")
		    err_str+=("$key_file")
		elif [ "$usekey" = "no" ]; then
		    retained_status+=("Valid")
		    retained_status+=("Not Valid")
		    err_str+=("$cert_file")
		    err_str+=("No read permissions.")
		fi
	    fi
	elif [[ (! -f $cert_file) && (! -f $key_file) ]]; then
	    retain="Failed"
	    retained_status+=("No")
	    retained_status+=("No")
	    err_str+=("Certificate file \"$cert_file\" is not found.")
	    err_str+=("Key file \"$key_file\" is not found.")
	elif [[ (! -f $cert_file) ]]; then
            retain="Failed"
            retained_status+=("No")
            retained_status+=("Yes")
            err_str+=("Certificate file \"$key_file\" is not found.")
            err_str+=("$key_file")
	elif [[ (! -f $key_file) ]]; then
	    retain="Failed"
	    retained_status+=("Yes")
	    retained_status+=("No")
	    err_str+=("$cert_file")
	    err_str+=("Key file \"$key_file\" is not found.")
	fi
    else
	retained_status+=("Yes")
        retained_status+=("Yes")
	err_str+=("No SSL Configured, Self signed certificate will be created.")
	err_str+=("No SSL Configured, Self signed certificate will be created.")
    fi

    #Print the table for Each Parameter
    print_configuration $1
    if [ "$retain" = "Success" ]; then
	LGTO_OLDCONF="$OLDCONF"
	LGTO_OLDCONFVER="$OLDCONFVER"
	LGTO_HTTPPORT="$DEFAULT_BASEPORT"
	LGTO_GSTPORT="$DEFAULT_GSTPORT"
	LGTO_DBSRVPORT="$DEFAULT_DBSRVPORT"
	LGTO_DATADIR="$DEFAULT_DBDIR"
	LGTO_AUTHHOST="$DEFAULT_AUTHHOST"
	LGTO_AUTHPORT="$DEFAULT_AUTHPORT"

	if [ "$1" = "console" ]; then
	    echo -e "\n\nValidation Success, Configuration can be retained during upgrade."
	else
	    echo "Validation Success, Configuration would be retained during upgrade." >> "$instlog"
	fi
    else
	if [ "$1" = "console" ]; then
	    echo -e "\n\nValidation Failed, Configuration can not retained during upgrade."
	else
	    echo "Validation Failed, Configuration can not retained during upgrade." >> "$instlog"
	fi
    fi
}

#
# Function:
# validport
#
# Description:
#	Prompt for a TCP/IP port number and optionally validate
#	that the port is not in use.
#
# Arguments:
#
#   Parameter			Purpose
#----------------------	--------------------------------------------
# Returns:
#
#   Return Variable		Purpose
#----------------------	--------------------------------------------
#
validport()
{
    port=$1
    validporterrstr=

    # Verify that number is numeric
    expr $port + 1 > /dev/null 2>&1
    if [ $? -ne 0 ]; then
	validporterrstr="${port} is not a valid port number."
	return 1
    fi
    if [ $port -lt 1024 -o $port -gt 49151 ]; then
	validporterrstr="Valid port range is between 1024 and 49151."
	return 1
    fi

    if  `which netstat &> /dev/null` ; then
	inuse=`netstat -na|grep " LISTEN"|grep  "[.:]${port} "`
    else
	# netstat command is deprecated , ss command is to be used.
	inuse=`ss -a|grep " LISTEN"|grep  "[.:]${port} "`
    fi

    if [ ! -z "${inuse}" ]; then
	validporterrstr="Port ${port} is already in use."
	return 1
    fi
    return 0
}

#
# Function:
#   is_ascii_path
#
# Description:
#   Checks if the specified path is ascii
#
# Arguments:
#
#   Parameter	    Purpose
#   ----------------------  --------------------------------------------
#   test_path	    path to check
# Returns:
#
#   Return Variable	Purpose
#   ----------------------  --------------------------------------------
#   result	    y or n
#
is_ascii_path()
{
    test_path=$1
    # empty out all acceptable characters
    result_temp_path=`echo $test_path | sed 's?[a-zA-Z0-9\^\?_/\$&:!,\.\(\)\*=~# @\+%-]??g'`
    # Check if there are any characters still present
    if [ "X$result_temp_path" != "X" ]; then
    result=n
    else
    result=y
    fi
}

validatedbdir()
{
    datadir="$DEFAULT_DBDIR"
    parent=`dirname "$datadir"`
    if [ -d "$parent" ] ; then
	#check if database exists
        if [ -d "$datadir/$DBNAME" ]; then
            # Make sure database files owner matches database user that was specified.
            chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$DEFAULT_DBDIR" >>  "$instlog" 2>&1

            if [ $? -ne 0 ] ; then
                echo "Could not change owner of $DEFAULT_DBDIR to $LGTO_NMCUSER" >>  "$instlog"
                exit 1
            fi

            DBOWNER=`ls -l ${datadir}/${DBSUBDIR} | grep "$DBTBLSPC" | awk -F " " '{ print $3 }'`
            if [ -z "$DBOWNER" ]; then
                # Skip the check if we cannot find the user
                echo "WARNING: Unable to find owner of $datadir/$DBNAME" >>  "$instlog"
                exit 1
            fi

            if [ "$DBOWNER" = "root" ]; then
                echo
                echo "ERROR: $datadir is owned by root" >>  "$instlog"
                exit 1
            fi

            #check for postgres db version. If its greater than 9, it needs to be upgraded
            POSTGRESDBVERSION=`cat "$datadir/$DBSUBDIR/PG_VERSION" 2>/dev/null`
            if [[ ("$POSTGRESDBVERSION" == "9.2") || ("$POSTGRESDBVERSION" == "11") || ("$POSTGRESDBVERSION" == "12") ]]; then
                LGTO_POSTGRES_UPGRADE="Y"
                LGTO_OVERWRITE="N"
                if [ "$POSTGRESDBVERSION" == "9.2" ]; then
                    postgres_version="9.2"
                elif [ "$POSTGRESDBVERSION" == "11" ]; then
                    postgres_version="11.21"
                elif [ "$POSTGRESDBVERSION" == "12" ]; then
                    postgres_version="12.18"
                fi
            fi
            LGTO_DBUSER=$LGTO_NMCUSER
        else # -d "$datadir/$DBNAME" = false
	    if [  -d "$datadir" ]; then
		if [ ! -z "$(ls -A $datadir)" ] ; then
		    echo "ERROR: $datadir is not empty. Database directory should be an empty directory" >>  "$instlog"
		    exit 1
		fi
	    fi
        fi
    else # -d "$parent" = false
	echo "Creating directory $parent" >> "$instlog"
	mkdir -p "$parent" >> "$instlog" 2>&1
	if [ $? -ne 0 ] ; then
	    echo "Could not create $parent" >> "$instlog"
	    exit 1
	fi
    fi

    LGTO_DATADIR="$datadir"
}

#
# Function:
#   create_nmcuser
#
# Description:
#   Create new user
#
# Arguments:
#
#   Parameter	    Purpose
#   ----------------------  --------------------------------------------
#   $1		The user name to be created
#
# Returns:
#
#   Return Variable	Purpose
#   ----------------------  --------------------------------------------
#
create_nmcuser()
{
    user_name=$1
    echo "Creating the non-root local user account \"$user_name\" ..." >> "$instlog"

    # if user default group exists; need to use -g option
    getent group "$user_name" > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
	useradd -s /sbin/nologin -d ${base} -g $user_name "$user_name" >> "$instlog" 2>&1
    else
	useradd -s /sbin/nologin -d ${base} "$user_name" >> "$instlog" 2>&1
    fi
    if [ $? -ne 0 ] ; then
	echo "ERROR: Could not create user $user_name." >> "$instlog"
	exit 1
    fi
}

#
# Function:
#       createcert
#
# Description:
#       Creates the SHA-2 certificate for https configuration.
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#
createcert()
{
    use_exist_cert="false"
    echo
    echo "Creating new certificate for https configuration." >> "$instlog"
    echo
    runcmd $gstconfig -c
}


#
# Function:
#       validatecert
#
# Description:
#       Valiates the certificate file.
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#
validatecert()
{
    usecert="yes"
    usekey="yes"
    owner=`stat -c %U $cert_file`
    if [ "$owner" != "nsrnmc" ]; then
        or=`ls -l $cert_file | cut -c8`
        if [ $or = '-' ]; then
            usecert="no"
        fi
    fi
    owner=`stat -c %U $key_file`
    if [ "$owner" != "nsrnmc" ]; then
        or=`ls -l $key_file | cut -c8`
        if [ $or = '-' ]; then
            usekey="no"
        fi
    fi
    if [[ ("$usecert" = "yes") && ("$usekey" = "yes") ]];then
        $gstconfig -f "$cert_file" -k "$key_file" -v >> "$instlog" 2>&1
        error_number=$?
        if [ $error_number -eq 0 ]; then
            echo "Successfully validated certificate & key file." >> "$instlog"
        elif [ $error_number -eq 2 ]; then
            echo "NMC HTTPS configuration does not support SHA1 based certificate." >> "$instlog"
        elif [ $error_number -eq 3 ]; then
            echo "Key file \"$key_file\" does not correspond to certificate file \"$cert_file\"." >> "$instlog"
        else
	    echo "$cert_file is not a valid certificate." >> "$instlog"
        fi
    elif [[ ("$usecert" = "no") || ("$usekey" = "no") ]]; then
        error_number=-1
    fi
}

#
# Function:
#       genhttpscertkey
#
# Description:
#       Read the cert file and key from httpd.conf and if its valid, its retained
#		otherwise new certificate is created.
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#
genhttpscertkey()
{
    if [[ ($install_type -eq 0) || ($install_type -eq 1) ]]; then
	echo "A self signed certificate would be created for this installation." >> "$instlog"
	createcert
    fi
}

#
# Function:
#	runcmd
#
# Description:
#	Runs the command and arguments specified by the positional
#	parameters, and logs the output to $instlog. If the command
#	returns a non-zero exit status, this script exits with a
#	status of 1.
#
# Arguments:
#
#	Parameter		Purpose
#	----------------------	--------------------------------------------
#	$1			Command to execute.
#	$2, $3, ...		Command arguments.
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#
runcmd()
{
    echo "** running: $*" >> "$instlog"
    $* >> "$instlog" 2>&1
    if [ $? -ne 0 ] ; then
	echo "ERROR: Command $* failed!" >> "$instlog"
	exit 1
    fi
}
#
# Function:
#   initenv
#
# Description:
#	Initialize the environment for upgrades.
#	Create logs folder, add permissions etc.
#
# Arguments:
#
#   Parameter	    Purpose
#   ----------------------  --------------------------------------------
#
# Returns:
#
#   Return Variable	Purpose
#   ----------------------  --------------------------------------------
#
initenv()
{
    # create apache logs directory
    mkdir -p "$apachelogs"
    if [ $? -ne 0 ] ; then
	echo "Could not create $apachelogs" >> "$instlog"
	exit 1
    fi
    rm -rf "${base}/postgres_latest"
    ln -sf "${base}/postgres/16.8" "${base}/postgres_latest"

    ##Check if nsrnmc user exist otherwise create
    result="invalid"
    valid_user_group "$LGTO_NMCUSER"
    if [ "$result" != "valid" ]; then
	create_nmcuser "$LGTO_NMCUSER"
    fi
    LGTO_NMCGROUP=`groups $LGTO_NMCUSER | cut -d ":" -f 2 | cut -d " " -f 2`
    chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$gstlogs" >>  "$instlog" 2>&1
    chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$apachelogs" >>  "$instlog" 2>&1

    for file in "${acmlcbfiles[@]}"
    do
	if [ -f ${gstcst}/${file} ]; then
	    chown "$LGTO_NMCUSER":"$LGTO_NMCUSER" "${gstcst}/${file}" >>  "$instlog" 2>&1
	    if [ $? -ne 0 ] ; then
		echo "Could not change owner of ${gstcst}/${file} to $LGTO_NMCUSER"
		exit 1
	    fi
	fi
    done

    if [ -f "$gstetc/cakey.pem" ]; then
	chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$gstetc/cakey.pem" >>  "$instlog" 2>&1
	if [ $? -ne 0 ] ; then
	    echo "Could not change owner of $gstetc/cakey.pem to $LGTO_NMCUSER" >>  "$instlog"
	    exit 1
	fi
    fi


    # Set LD_LIBRARY_PATH
    case "$ARCH" in
	Linux )
       LD_LIBRARY_PATH="${nsrbase}/lib/nsr/lib64/:$LD_LIBRARY_PATH"
       export LD_LIBRARY_PATH
       ;;
    esac

    #In case of upgrade, postun linux scripts deletes the help folder so extracting
    if [ ! -d "${gstweb}/help" ]; then
	runcmd tar xzf "${gstweb}/onlinehelp.tgz" -C "${gstweb}" --no-same-owner >> "$instlog" 2>&1
	runcmd chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "${gstweb}/help" >>  "$instlog" 2>&1
    fi
    # Change install prefix for modules in httpd.conf
    runcmd cp -f "$apacheconf" "$apacheconfbak"
    runcmd rm -f "$apacheconf"
    sed -e "s,/opt/lgtonmc/apache/modules/,$base/apache/modules/,g" < "$apacheconfbak" > "$apacheconf"
    runcmd rm -f "$apacheconfbak"
    chown "$LGTO_NMCUSER":"$LGTO_NMCUSER" "${apacheconf}" >>  "$instlog" 2>&1
    if [ $? -ne 0 ] ; then
	echo "Could not change owner of ${apacheconf} to $LGTO_NMCUSER" >>  "$instlog"
	exit 1
    fi

    # Set LD_LIBRARY_PATH
    case "$ARCH" in
	    Linux )
	LD_LIBRARY_PATH="${bindir}:${pgodbclib}:$LD_LIBRARY_PATH"
	export LD_LIBRARY_PATH
	;;
    esac

    # configure system
    # Make previous .gstd.conf file the current one
    if [ "X" != "X$LGTO_OLDCONF" ]; then
	runcmd cp -f "$LGTO_OLDCONF" "$gstconf"
    fi
    DEFAULT_NSRDIR="$nsrbase/sbin"

    if [ -f "$DEFAULT_NSRDIR/nsrexecd" ]; then
	LGTO_NSRDIR="$DEFAULT_NSRDIR"
    else
	echo "NW Client Install directory not found" >> "$instlog"
	exit 1
    fi
}
#
# Function:
#   print_configuration
#
# Description:
#	Print the config parameters in tabular column.
#
# Arguments:
#
#   Parameter	    Purpose
#   ----------------------  --------------------------------------------
#
# Returns:
#
#   Return Variable	Purpose
#   ----------------------  --------------------------------------------
#
print_configuration()
{
    if [ "$1" = "console" ]; then
	echo -e "\n\n==========================="
	echo " Configuration Status (NMC)"
	echo -e "===========================\n\n"
	printf "%-20s %-10s %-15s" "Parameter" "Retained" "Value/Reason"
	printf "\n\n"
    else
	echo -e "\n\n===========================" >> "$instlog"
	echo " Configuration Status (NMC)" >> "$instlog"
	echo -e "===========================\n\n" >> "$instlog"
	printf "%-20s %-10s %-15s" "Parameter" "Retained" "Value/Reason" >> "$instlog"
	printf "\n\n" >> "$instlog"
    fi

    total=${#config_params[*]}
    for (( i=1; i<=$(( $total -1 )); i++ ))
	do
	    if [ "$1" = "console" ]; then
		printf "%-20s %-10s %-15s" "${config_params[$i]}" "${retained_status[$i]}" "${err_str[$i]}"
		printf "\n"
	    else
		printf "%-20s %-10s %-15s" "${config_params[$i]}" "${retained_status[$i]}" "${err_str[$i]}" >> "$instlog"
		printf "\n" >> "$instlog"
	    fi
	done
}

#
# main
#
PATH="/bin:/usr/bin:/sbin:/usr/sbin:$PATH"
export PATH
ARCH=`uname`
INIT_SYSTEM=`ps -p 1 -o comm=`
PKG="LGTOnmc"
DBSUBDIR="pgdata"
DBTBLSPC="pg_tblspc"
DBNAME="$DBSUBDIR/$DBTBLSPC"
DBCONF_FILE=gstd_db.conf
NETWORKER_STARTED="false"
LGTO_NMCUSER=nsrnmc
jconnjar="/${PKG}/java/postgresql-42.7.3.jar"
case "$ARCH" in
    Linux )
	base=/opt/lgtonmc
	if [ ! -f "$base/bin/gstd" ]; then
	    echo "ERROR: Unable to get install directory. File $base/bin/gstd not found."
	    exit 1
	fi
        nsrbase=`rpm -q --qf "%{INSTPREFIXES}\n" lgtoclnt 2> /dev/null`
        if [ ! -f "$nsrbase/sbin/nsrexecd" ]; then
			nsrbase="/usr"
        fi
        ;;
esac
acmlcbfiles=("acm_lb.clb" "acm_lb.clb.bak" "acm_lb.clb.bak.FCD" "acm_lb.clb.FCD" "acm_lb.cred")
savepsm="${base}/bin/savepsm"
gstparam="${base}/bin/gstparam"
gstetc="${base}/etc"
dbupgr="${base}/bin/gstdbupgrade.sh"
gstconf="${base}/etc/gstd.conf"
gstd="${base}/bin/gstd"
gstping="${base}/bin/gstping"
gstconfig="${base}/bin/gstconfig"
gstlocalize="${base}/bin/gst_localize"
gstdbinit="${base}/bin/gstdbinit"
gstauthcfg="${base}/bin/gstauthcfg"
gstlogs="${base}/logs"
gstcst="${base}/cst"
apachelogs="${base}/apache/logs"
apacheconf="${base}/apache/conf/httpd.conf"
apacheconfbak="${base}/apache/conf/httpd.conf.bak"
instlog="${gstlogs}/install.log"
gstweb="${base}/web"
gstmod="${base}/mod"
stparam_file="${gstweb}/params.html"
gstjar="/${PKG}/java/gst.jar"
gwtjar="/${PKG}/java/gwt.jar"
gwtresjar="/${PKG}/java/gwt_res.jar"
comtskjar="/${PKG}/java/comtsk.jar"
initfile="${gstetc}/gst"
systemdfile="${gstetc}/gst.service"
systemdscript="${gstetc}/gst_linux.sh"
savepsmsh="${gstetc}/savepsm.sh"
httpsconfig="${base}/apache/conf/.https.conf"
pglib="${base}/postgres_latest/lib"
pgbin="${base}/postgres_latest/bin"
postgreslatestversion="16"
pg92bin="${base}/postgres/9.2/bin"
pgodbclib="${base}/postgres_latest/odbc"
bindir="${base}/bin"
jaxpjar="/${PKG}/java/jaxp.jar"
jcchartjar="/${PKG}/java/jcchart.jar"
jcfieldjar="/${PKG}/java/jcfield.jar"
jcpagelayoutjar="/${PKG}/java/jcpagelayout.jar"
formsjar="/${PKG}/java/forms.jar"
looksjar="/${PKG}/java/looks.jar"
antlrjar="/${PKG}/java/antlr.jar"
yfilesjar="/${PKG}/java/y.jar"
ysvgjar="/${PKG}/java/ysvg.jar"
batikjar="/${PKG}/java/batik.jar"
jide_commonjar="/${PKG}/java/jide-common.jar"
jide_componentsjar="/${PKG}/java/jide-components.jar"
jide_dockjar="/${PKG}/java/jide-dock.jar"
data_domainjar="/${PKG}/java/ddomain.jar"
data_domainresjar="/${PKG}/java/ddomain_res.jar"
json_simplejar="/${PKG}/java/json-simple-1.1.1.jar"
gemsjar="/${PKG}/java/gconsole.jar"
gemsresjar="/${PKG}/java/gconsole_res.jar"
nwjar="/${PKG}/java/nwadmin.jar"
nwresjar="/${PKG}/java/nwadmin_res.jar"
nwoldjar="/${PKG}/java/nwadmin_old.jar"
fsrajar="/${PKG}/java/fsra.jar"
fsraresjar="/${PKG}/java/fsra_res.jar"
db2rajar="/${PKG}/java/db2ra.jar"
db2raresjar="/${PKG}/java/db2ra_res.jar"
ifmxrajar="/${PKG}/java/ifmxra.jar"
ifmxraresjar="/${PKG}/java/ifmxra_res.jar"
nmlrajar="/${PKG}/java/nmlra.jar"
nmlraresjar="/${PKG}/java/nmlra_res.jar"
nmmexchrajar="/${PKG}/java/nmmexchra.jar"
nmmexchraresjar="/${PKG}/java/nmmexchra_res.jar"
nmmhypervrajar="/${PKG}/java/nmmhypervra.jar"
nmmhypervraresjar="/${PKG}/java/nmmhypervra_res.jar"
nmmsprajar="/${PKG}/java/nmmspra.jar"
nmmspraresjar="/${PKG}/java/nmmspra_res.jar"
nmsqlrajar="/${PKG}/java/nmsqlra.jar"
nmsqlraresjar="/${PKG}/java/nmsqlra_res.jar"
fdiffjar="/${PKG}/java/fdiff.jar"
fdiffresjar="/${PKG}/java/fdiff_res.jar"
nworajar="/${PKG}/java/nwora.jar"
nworaresjar="/${PKG}/java/nwora_res.jar"
saprajar="/${PKG}/java/sapra.jar"
sapraresjar="/${PKG}/java/sapra_res.jar"
sybrajar="/${PKG}/java/sybra.jar"
sybraresjar="/${PKG}/java/sybra_res.jar"
hanarajar="/${PKG}/java/hanara.jar"
hanararesjar="/${PKG}/java/hanara_res.jar"
mysqlrajar="/${PKG}/java/mysqlra.jar"
mysqlraresjar="/${PKG}/java/mysqlra_res.jar"
config_params=('Version1.0' 'HTTP Port' 'GST Server Port' 'DB Port' 'DB Directory' 'AUTHC Host' 'AUTHC Port' 'Certificate File' 'Key File')
umask 0022

if [ ! -z "$1" ]; then
	if [ "$1" = "--validate-config" ]; then
		readexistingconfig console
		validateconfig console
		exit 0
	elif [ "$1" = "--help" ]; then
		echo
		echo "=============================="
		echo "NMC Retain Script for Upgrades"
		echo "=============================="
		echo "Usage:"
		echo -e "nmc_retain_config --validate-config:\t Validates the existing configuration."
		echo -e "nmc_retain_config --help:\t\t Show this screen"
		echo
		exit 0
	fi
fi

# create logs directory
mkdir -p "$gstlogs"
if [ $? -ne 0 ] ; then
    export "Could not create $gstlogs"
    exit 1
fi

# Insert install date in logfile
echo "  " >> "$instlog"
echo "Retain Configuration Upgrade begins `date`" >> "$instlog"
echo "  " >> "$instlog"

# Insert OS version in logfile
echo "  " >> "$instlog"
echo "OS Version is `uname -a`" >> "$instlog"
echo "  " >> "$instlog"

# Read Existing Configuration and see whether it can be retained.
readexistingconfig

# Validate the configuration. If retain=Success, then proceed otherwise exit.
validateconfig

if [[ "$retain" == "Success" ]] ; then
    #Initialize the Environment for upgrades
    authc=`rpm -qa | grep lgtoauthc 2> /dev/null`
    initenv
    genhttpscertkey
    validatedbdir

    if [ ! -d "$LGTO_DATADIR" ] ; then
	echo "Creating directory $LGTO_DATADIR" >> "$instlog"
	mkdir -p "$LGTO_DATADIR" >> "$instlog" 2>&1
	if [ $? -ne 0 ] ; then
	    echo "Could not create $LGTO_DATADIR" "$instlog"
	    exit 1
	fi
	LGTO_DBUSER=$LGTO_NMCUSER
	chown $LGTO_DBUSER "$LGTO_DATADIR" >> "$instlog" 2>&1
	if [ $? -ne 0 ] ; then
	    echo "Could not change owner of $LGTO_DATADIR to $LGTO_DBUSER" >> "$instlog"
	    exit 1
	fi
	chmod 700 "$LGTO_DATADIR" >> "$instlog" 2>&1
	if [ $? -ne 0 ] ; then
	    echo "Could not change permissions of $LGTO_DATADIR" >> "$instlog"
	    exit 1
	fi
    fi

    # call postgres upgrade if older version found
    if [ "$LGTO_POSTGRES_UPGRADE" == "Y" ]; then
	echo "NOTE" >> "$instlog"
	echo "====" >> "$instlog"
	pglastbin="${base}/postgres/${postgres_version}/bin"
	echo "Postgres $POSTGRESDBVERSION database detected. It will be migrated to Postgres $postgreslatestversion" >> "$instlog"
	echo "It may take a while to upgrade....." >> "$instlog"

	#Run gstdbinit in upgrade mode to upgrade the db.
	pglatesttmpdir="$datadir""$postgreslatestversion"
	echo "Using $pglatesttmpdir as Postgres $postgreslatestversion temp data directory" >> "$instlog" 2>&1
	"$gstdbinit" -u -i -c -b "$pglastbin" -B "$pgbin" -t "$datadir" -T "$pglatesttmpdir" -n "$DEFAULT_DBSRVPORT" -N "$DEFAULT_DBSRVPORT" -U "$LGTO_DBUSER" >> "$instlog" 2>&1
	if [ $? -eq 0 ]; then
	    #upgrade successful
	    echo "Upgrade to Postgres $postgreslatestversion Successful" >> "$instlog"
	    mv "$datadir/gstd_db.conf" "$pglatesttmpdir/gstd_db.conf" >> "$instlog" 2>&1
	    chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$pglatesttmpdir/gstd_db.conf" >>  "$instlog" 2>&1
	    rm -rf "$datadir" >> "$instlog" 2>&1
	    mv "$pglatesttmpdir" "$datadir" >> "$instlog" 2>&1
	else
	    #upgrade failed, make postgres_latest point to older bin
	    echo
	    echo "Migration to Postgres $postgreslatestversion Failed. NMC will run with $POSTGRESDBVERSION database" >> "$instlog"
	    echo "See install.log and pg_upgrade_*.log in logs directory for more details." >> "$instlog"
	    echo
	    echo "Upgrade to Postgres $postgreslatestversion Failed. Failover to $POSTGRESDBVERSION binaries so that db can start" >> "$instlog"
	    rm -f "${base}/postgres_latest" >>  "$instlog" 2>&1
	    ln -sf "${base}/postgres/${postgres_version}" "${base}/postgres_latest" >> "$instlog" 2>&1
	fi
    fi

	runcmd "$gstparam" -f "$gstconf" -d -n pkg_lang_packs
	runcmd "$gstparam" -f "$gstconf" -d -n pkg_langjar_files

	runcmd "$gstparam" -f "$gstconf" -d -n http_svc_port
	runcmd "$gstparam" -f "$gstconf" -a -n http_svc_port -t int -v $LGTO_HTTPPORT

	runcmd "$gstparam" -f "$gstconf" -d -n clnt_svc_port
	runcmd "$gstparam" -f "$gstconf" -a -n clnt_svc_port -t int -v $LGTO_GSTPORT

	runcmd "$gstparam" -f "$gstconf" -d -n db_svc_port
	runcmd "$gstparam" -f "$gstconf" -a -n db_svc_port -t int -v $LGTO_DBSRVPORT

	runcmd "$gstparam" -f "$gstconf" -d -n snmp_trapd_enable
	runcmd "$gstparam" -f "$gstconf" -a -n snmp_trapd_enable -t int -v 1

	runcmd "$gstparam" -f "$gstconf" -d -n module_dir
	runcmd "$gstparam" -f "$gstconf" -a -n module_dir -t string -v "$gstmod"

	runcmd "$gstparam" -f "$gstconf" -d -n pkg_web_dirmap
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_web_dirmap -t list -l \
		-n alias -t string -v "/$PKG" -n path -t string -v "$gstweb"

	runcmd "$gstparam" -f "$gstconf" -d -n pkg_jar_files
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$gstjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$gwtjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$gwtresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$comtskjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jconnjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jaxpjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jcchartjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jcfieldjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jcpagelayoutjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$formsjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$looksjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$antlrjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$yfilesjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$ysvgjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$batikjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jide_commonjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jide_componentsjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$jide_dockjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$data_domainjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$data_domainresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$json_simplejar"

	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$gemsjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$gemsresjar"

	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nwjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nwresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nwoldjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$fsrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$fsraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$db2rajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$db2raresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$ifmxrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$ifmxraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmlrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmlraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmmexchrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmmexchraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmmhypervrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmmhypervraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmmsprajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmmspraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmsqlrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nmsqlraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$fdiffjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$fdiffresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nworajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$nworaresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$saprajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$sapraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$sybrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$sybraresjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$hanarajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$hanararesjar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$mysqlrajar"
	runcmd "$gstparam" -f "$gstconf" -a -n pkg_jar_files -t string -v "$mysqlraresjar"

	runcmd "$gstparam" -f "$gstconf" -d -n web_server_user
	runcmd "$gstparam" -f "$gstconf" -a -n web_server_user -t string -v "$LGTO_NMCUSER"
	runcmd "$gstparam" -f "$gstconf" -d -n web_server_group
	runcmd "$gstparam" -f "$gstconf" -a -n web_server_group -t string -v "$LGTO_NMCGROUP"

	runcmd "$gstparam" -f "$gstconf" -d -n gst_postgres_user
	runcmd "$gstparam" -f "$gstconf" -a -n gst_postgres_user -t string -v "$LGTO_DBUSER"

	runcmd "$gstparam" -f "$gstconf" -d -n nsr_nmc_user
	runcmd "$gstparam" -f "$gstconf" -a -n nsr_nmc_user -t string -v "$LGTO_NMCUSER"

	runcmd "$gstparam" -f "$gstconf" -d -n authsvc_hostname

	if [ ! -z "$LGTO_AUTHHOST"  ] ; then
		runcmd "$gstparam" -f "$gstconf" -a -n authsvc_hostname -t string -v "$LGTO_AUTHHOST"
	fi
	runcmd "$gstparam" -f "$gstconf" -d -n authsvc_port
	if [ ! -z "$LGTO_AUTHPORT"  ] ; then
		runcmd "$gstparam" -f "$gstconf" -a -n authsvc_port -t int -v $LGTO_AUTHPORT
	fi

	runcmd "$gstparam" -f "$gstconf" -d -n jre_location

	echo "Configuring current_db_dir to $LGTO_DATADIR in gstd.conf" >> "$instlog"
	"$gstparam" -f "$gstconf" -d -n current_db_dir
	"$gstparam" -f "$gstconf" -a -n current_db_dir -t string -v "$LGTO_DATADIR" >> "$instlog" 2>&1
	if [ $? -ne 0 ] ; then
		echo "Failed to configure current_db_dir to $LGTO_DATADIR in $gstconf" >> "$instlog"
		exit 1
	fi
	# configure component files
	runcmd "$gstconfig"
	if [ -f "${gstetc}/.odbc.ini" ]; then
		chown "$LGTO_NMCUSER":"$LGTO_NMCUSER" "${gstetc}/.odbc.ini" >>  "$instlog" 2>&1
		if [ $? -ne 0 ] ; then
			echo "Could not change owner of ${gstetc}/.odbc.ini to $LGTO_NMCUSER" >> "$instlog"
			exit 1
		fi
	fi

	# Configure Startup parameters file
	# Create the file if required
	if [ ! -f "$stparam_file" ] ; then
		echo "{" > "$stparam_file"
		echo "};" >> "$stparam_file"
	fi
	runcmd "$gstparam" -f "$stparam_file" -d -n initial_launch
	if [ "$LGTO_OVERWRITE" != "N" ] ; then
		runcmd "$gstparam" -f "$stparam_file" -a -n initial_launch -t boolean -v true
		runcmd "$gstparam" -f "$stparam_file" -d -n "GST_LOGON_BANNER"
		"$gstparam" -f "$stparam_file" -a -n "GST_LOGON_BANNER" -t string -v "Warning: Authorized user only" >> "$instlog" 2>&1
		if [ $? -ne 0 ] ; then
			echo "Failed to configure GST_LOGON_BANNER in $stparam_file" >>  "$instlog"
			exit 1
		fi
	else
		runcmd "$gstparam" -f "$stparam_file" -a -n initial_launch -t boolean -v false
	fi

	if [ -f "${stparam_file}" ]; then
		chown "$LGTO_NMCUSER":"$LGTO_NMCUSER" "${stparam_file}" >>  "$instlog" 2>&1
		if [ $? -ne 0 ] ; then
			echo "Could not change owner of ${stparam_file} to $LGTO_NMCUSER" >> "$instlog"	
			exit 1
		fi
	fi

	# setup /etc/init.d files/links
	echo "** Creating gst rc file **" >> "$instlog"

	if [ "$ARCH" = "Linux" ] ; then
		sed -e "s,^GST_HOME=.*,GST_HOME=$base," -e "s,^NSR_HOME=.*,NSR_HOME=$nsrbase," < "$initfile" > /opt/lgtonmc/etc/tmp_file ; mv /opt/lgtonmc/etc/tmp_file /opt/lgtonmc/etc/gst
		if [ $? -ne 0 ] ; then
		echo "Could not create init.d script- /opt/lgtonmc/etc/gst" >> "$instlog"
		exit 1
		fi

		sed -e "s,^GST_HOME=.*,GST_HOME=$base," -e "s,^NSR_HOME=.*,NSR_HOME=$nsrbase," < "$systemdscript" > /opt/lgtonmc/etc/tmp_file ; mv /opt/lgtonmc/etc/tmp_file /opt/lgtonmc/etc/gst_linux.sh
		if [ $? -ne 0 ] ; then
			echo "Could not create systemd scripts in /opt/lgtonmc/etc" >> "$instlog"
			exit 1
		fi
		chown "$LGTO_NMCUSER":"$LGTO_NMCUSER" /opt/lgtonmc/etc/gst >>  "$instlog" 2>&1
		chown "$LGTO_NMCUSER":"$LGTO_NMCUSER" /opt/lgtonmc/etc/gst_linux.sh >>  "$instlog" 2>&1
		if [ "$INIT_SYSTEM" == "init" ]; then
			runcmd chmod 744 /opt/lgtonmc/etc/gst
			runcmd /bin/cp /opt/lgtonmc/etc/gst /etc/init.d/gst
			runcmd chkconfig --add gst
			# Post processing to take care of bug 161870 in chkconfig 1.3.13.2
			STARTLEVELS="3 5"
			STOPLEVELS="0 1 2 6"
			for i in ${STARTLEVELS}; do
			    if [ -f /etc/rc.d/rc${i}.d/S-1gst ]; then
					runcmd mv /etc/rc.d/rc${i}.d/S-1gst /etc/rc.d/rc${i}.d/S97gst
			    fi
			done
			for i in ${STOPLEVELS}; do
			    if [ -f /etc/rc.d/rc${i}.d/K-1gst ]; then
					runcmd mv /etc/rc.d/rc${i}.d/K-1gst /etc/rc.d/rc${i}.d/K03gst
			    fi
			done
		fi

		if [ "$INIT_SYSTEM" == "systemd" ]; then
			runcmd chmod 744 /opt/lgtonmc/etc/gst_linux.sh

			if [ -f /usr/lib/systemd/system/gst.service ]; then
			    # Delete old copy to reflect new file permission post upgrade
			    runcmd rm -f /usr/lib/systemd/system/gst.service
			fi
			runcmd /bin/cp /opt/lgtonmc/etc/gst.service /usr/lib/systemd/system/
			runcmd /usr/bin/systemctl --no-reload disable gst.service > /dev/null 2>&1
			runcmd /usr/bin/systemctl enable gst.service > /dev/null 2>&1
			runcmd /usr/bin/systemctl daemon-reload > /dev/null 2>&1
		fi
	fi

	echo "** Copying savepsm to $LGTO_NSRDIR **" >> "$instlog"
	runcmd rm -f $LGTO_NSRDIR/savepsm
	runcmd /bin/cp $savepsm $LGTO_NSRDIR
	echo "** Copying savepsm.sh to $LGTO_NSRDIR **" >> "$instlog"
	runcmd rm -f $LGTO_NSRDIR/savepsm.sh
	sed -e "s,XGST_INSTALL_DESTDIRX,$base,
	    s,XNSR_BIN_PATHX,$LGTO_NSRDIR," < "$savepsmsh" > $LGTO_NSRDIR/savepsm.sh
	if [ $? -ne 0 ] ; then
		echo "Could not create $LGTO_NSRDIR/savepsm.sh"
		exit 1
	fi
	runcmd chmod 755 "$LGTO_NSRDIR/savepsm.sh"

	# Run the localization command
	runcmd "$gstlocalize"

	#check if ldap has been configured
	if [ -f ${gstcst}/Config.xml ] ; then
		LDAPMODE=`cat ${gstcst}/Config.xml | grep "authorityName"`
	fi

	# For new database or non ldap mode, make sure auth method is always native
	if [ "$LGTO_OVERWRITE" != "N" -o -z "${LDAPMODE}" ] ; then
		if [ -f ${gstcst}/Config.xml ] ; then
			runcmd rm -f  ${gstcst}/Config.xml
		fi
		if [ -f ${gstcst}/csp.clb ]; then
			runcmd rm -f ${gstcst}/csp.clb
		fi
		if [ -f ${gstcst}/csp.clb.bak ] ; then
			runcmd rm -f ${gstcst}/csp.clb.bak
		fi
		if [ -f ${gstcst}/csp.clb.FCD ]; then
			runcmd rm -f ${gstcst}/csp.clb.FCD
		fi
		if [ -f ${gstcst}/csp.clb.bak.FCD ] ; then
			runcmd rm -f ${gstcst}/csp.clb.bak.FCD
		fi
		if [ -f ${gstcst}/csp.cred ] ; then
			runcmd rm -f ${gstcst}/csp.cred
		fi
		if [ -f ${gstcst}/CST_ActiveDirectory.props ] ; then
			runcmd rm -f ${gstcst}/CST_ActiveDirectory.props
		fi
		if [ -f ${gstcst}/upgrade_cst.tag ] ; then
			runcmd rm -f ${gstcst}/upgrade_cst.tag
		fi
	fi

	# If no previous CST Config.xml is present, copy from template
	if [ ! -f ${gstcst}/Config.xml ] ; then
		runcmd /bin/cp ${gstcst}/Config.xml.template ${gstcst}/Config.xml
	fi

	if [ -f "${gstcst}/Config.xml" ]; then
		chown "$LGTO_NMCUSER":"$LGTO_NMCUSER" "${gstcst}/Config.xml" >>  "$instlog" 2>&1
		if [ $? -ne 0 ] ; then
			echo "Could not change owner of ${gstcst}/Config.xml to $LGTO_NMCUSER"
			exit 1
		fi
	fi

	# If CST needs upgrading, drop the tag file in place
	if [ -s ${gstcst}/csp.clb ]; then
		touch ${gstcst}/upgrade_cst.tag
	fi

	# touch all the jar files, to force web start to refetch them
	for jarfile in ${gstweb}/java/*.jar; do
		touch $jarfile
	done

	# Delete any leftover db tmp files from previous install
	runcmd rm -f "/tmp/.s.PGSQL.${LGTO_DBSRVPORT}"
	runcmd rm -f "/tmp/.s.PGSQL.${LGTO_DBSRVPORT}.lock"

	# delete any old .gstd.conf file. Note that there could be more than
	# one. One left behind by %pre if rpm -U was done and one left behind by
	# %postun of the previous install
	if [ "X" != "X$LGTO_OLDCONF" ]; then
	    runcmd rm -f "${base}/etc/.gstd.conf.*"
	fi

	if [ -f ${gstlogs}/dbunloaded.tag ]; then
            runcmd rm -f ${gstlogs}/dbunloaded.tag
        fi

	pid=`pidof nsrexecd` >> "$instlog" 2>&1
	if [ -z "$pid" ]; then
	    echo "NetWorker services on this host are not running." >> "$instlog"
	    # Detect whether its a standalone installation or with NW Server
	    if [ -z "$authc" ]; then
		echo "Standalone NMC Installation detected, Starting Client Service." >> "$instlog"
		if [[ ("$ARCH" == "Linux") && ("$INIT_SYSTEM" == "systemd") ]]; then
		    /usr/bin/systemctl start networker.service
		else
		    service networker start
                fi
                sleep 8
		START_GST="automatic"
	    else
		echo "NMC installation is with NW Server." >> "$instlog"
		echo "Not attemping to start GST Service as NW Services are down." >> "$instlog"
		echo "After rpm installation is complete, Start Networker Services followed by GST Services" >> "$instlog"
		START_GST="manual"
		GST_SERVICE_STARTED="false"
	    fi
	else
	    echo "NetWorker services are running on this host." >> "$instlog"
	    START_GST="automatic"    
	fi

	if [ "$START_GST" = "automatic" ]; then
	    # Start the GST server
	    echo "Starting the GST server" >> "$instlog"
	    if [[ ("$ARCH" == "Linux") && ("$INIT_SYSTEM" == "systemd") ]]; then
		/usr/bin/systemctl start gst.service
		echo
		echo
	    else
		service gst start
		echo
		echo
	    fi

	    if [ $? -ne 0 ] ; then
		echo "Warning: Failed to start the gst daemon." >>  "$instlog"
		GST_SERVICE_STARTED="false"
	    else
		GST_SERVICE_STARTED="true"		
	    fi
	fi

	echo "The installation completed successfully." >> "$instlog"

	#if everything is successful, print the table for retain configuration
	print_configuration

cat<<-!

	NOTE: NMC existing configuration retained with following values.
	      In case if any of configuration values needs changes, please
	      re-run ${base}/bin/nmc_config

!
	print_configuration console

	if [ "$GST_SERVICE_STARTED" = "false" ]; then
cat<<-!

	======================================================================================
	NOTE: 
	Not Attempting to Start GST Services as NMC is installed along with NetWorker Server
	and NetWorker Services are not running. 

	After installation is complete, Please start NetWorker Service followed by GST Service
	=======================================================================================

!
	fi
	
	echo
	echo
else
	echo "Please run ${base}/bin/nmc_config after rpm installation." >> "$instlog"
	exit 1
fi
exit 0
