#! /bin/bash
#
# $Id$ Copyright (c) 2000-2025 EMC Corporation.
#

#
# Copyright (c) 2000-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.
#
ARCH=`uname`
INIT_SYSTEM=`ps -p 1 -o comm=`

#
# Function:
#	ask
#
# Description:
#	Prompts the user for data entry.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#	$1			The prompt string to display.
#	$2			The default value for return.
#	$3			The punctuation value for return.
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	result			The data entered by the user, or the value
#				of $default if the user accepted the default.
#
ask()
{
    prompt=$1
    default=$2
    punctuation=$3
    echo
    if [ -z "${default}" ]; then
	case "$ARCH" in
	    Linux ) echo -n "${prompt}${punctuation} ";;
	esac
    else
	case "$ARCH" in
	    Linux ) echo -n "${prompt} [${default}]${punctuation} ";;
	esac
    fi

    read ans
    if [ -z "$ans" ]; then
	result="$default"
    else
	result="$ans"
    fi
}

#
# Function:
#	yesno
#
# Description:
#	Prompts the user for a yes or no answer.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#	$1			The question to display.
#	$2			The default value, either 'y' or 'n'.
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	result			Value of 'y' or 'n'.
#
yesno()
{
    while true ; do
	ask "$1" "$2" "?"
	if [ `expr "X${result}" : 'X[yY]'` -ne 0 ]; then
	    result=y
	    break
	elif [ `expr "X${result}" : 'X[nN]'` -ne 0 ]; then
	    result=n
	    break
	else
	    echo "Please respond \`y' or \`n'"
	fi
    done
}

#
# Function:
#	validdir
#
# Description:
#	Checks validity of a directory.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#	$1			The prompt string to display.
#	$2			Default return value if no response.
#	$3			Verify directory existence, default no
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	result			Pathname to directory.
#
# Notes:
#
validdir()
{
    direxist=$3
    silent_install_processed="false"
    while true; do
	if [ $silent_install = "false" ]; then
	    ask "$1" "$2" ":"
	else
	    if [ $silent_install_processed = "false" ]; then
		result="$2"
		silent_install_processed="true";
	    else
		exit 1;
	    fi
	fi
	if [ `expr X${result} : 'X/'` -lt 1 ]; then
	    echo
	    echo "ERROR: \"${result}\" is not an absolute path."
	elif [ ! -z "${direxist}" -a "${direxist}" = "yes" ]; then
	    if [ ! -d "${result}" ]; then
	        echo
	        echo "ERROR: The specified directory does not exist."
	    else
		break
	    fi
	else
	    break
	fi
    done
    # result is set from ask()
}

#
# 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:
#	validport
#
# Description:
#	Prompt for a TCP/IP port number and optionally validate
#	that the port is not in use.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#	$1			The prompt string to display.
#	$2			The default value for return.
#	$3			1 if in use is okay, 0 if must be free.
#	$4			1 if use default w/o asking user, 0 otherwise
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	result			A valid port number.
#
validport()
{
    usedok=$3
    use_default=$4

    silent_install_processed="false"
    while true; do
	if [ $silent_install = "false" ]; then
	    # if use_default is specified, first  use it without asking
	    if [ $use_default -eq 1 ]; then
		result="$2"
	    else
	        ask "$1" "$2" ":"
	    fi
	else
	    use_default=0
	    if [ $silent_install_processed = "false" ]; then
		result="$2"
		silent_install_processed="true";
	    else
		exit 1;
	    fi
	fi

	# Verify that number is numeric
	expr $result + 1 > /dev/null 2>&1
	if [ $? -ne 0 ]; then
	    #Do not give error msg if we tried w/o asking the user
	    if [ $use_default -eq 1 ]; then
		use_default=0
		continue
	    fi
	    echo
	    echo "ERROR: ${result} is not a valid port number!"
	    continue
	fi

	if [ $result -lt 1024 -o $result -gt 49151 ]; then
	    #Do not give error msg if we tried w/o asking the user
	    if [ $use_default  -eq 1 ]; then
		use_default=0
		continue
	    fi
	    echo
	    echo "ERROR: Valid port range is between 1024 and 49151"
	    continue
	fi


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

	    if [ ! -z "${inuse}" ]; then
		#Do not give error msg if we tried w/o asking the user
		if [ $use_default -eq 1 ]; then
		    use_default=0
		    continue
		fi
		echo
		echo "WARNING: Port ${result} is already in use."
		if [ $silent_install = "true" ]; then
		    exit 1
		fi
		port=$result
		yesno "Do you wish to specify a different port number" y
		if [ "$result" = "n" ] ; then
		    result=$port
		    break
		fi
	    else
		break
	    fi
	fi
    done
    # result is set from ask()
}

#
# 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
}

#
# 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!"
	exit 1
    fi
}

#
# Function:
#	checkforupgrade
#
# Description:
#	Checks presence of old config file and reads its values
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_OLDCONF
#	LGTO_OLDCONFVER
#	DEFAULT_BASEPORT
#	DEFAULT_GSTPORT
#	DEFAULT_DBDIR
#	DEFAULT_DBUSER
#
checkforupgrade()
{
    # 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
	    if [ $silent_install = "false" ]; then
		echo
		echo "NOTE"
		echo "===="
		echo "Install has detected the configuration file of a previous lgtonmc"
		echo "package. Install will attempt to read the configuration parameters"
		echo "in this file and present them as default values where appropriate."
		echo "Please modify any value that is incorrect or needs to be changed."
		echo
	    fi

	    chownacmlcbfiles
	    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"`
	    # In the rare case, upgrade was done before nmc_config was run, reset GSTPORT
	    if [ -n "$DEFAULT_GSTPORT" -a "$DEFAULT_GSTPORT" = "1970" ]; then
		DEFAULT_GSTPORT=
	    fi
	    DEFAULT_DBSRVPORT=`awk '/db_svc_port/ { print substr($4,1,length($4)-1) }' "$OLDCONF"`
	    # For database pathname take care of situation where pathname has spaces
	    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"`
	    if [ -d "$DEFAULT_DBDIR" ]; then
		echo "Changing the ownership of $DEFAULT_DBDIR to $LGTO_NMCUSER" >>  "$instlog" 2>&1
                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"
                    exit 1
		fi
            fi
	    if [ ! -d "$DEFAULT_DBDIR/$DBNAME" ]; then
		DEFAULT_DBDIR=
	    fi
	    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"
                    exit 1
                fi
	    fi
	    if [ -f "$apacheconf" ]; then
                chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$apacheconf" >>  "$instlog" 2>&1
                if [ $? -ne 0 ] ; then
                    echo "Could not change owner of $apacheconf to $LGTO_NMCUSER"
                    exit 1
		fi
            fi

	    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"`

	    LGTO_OLDCONF="$OLDCONF"
	    LGTO_OLDCONFVER="$OLDCONFVER"
	fi
    fi
}

#
# Function:
#       chownacmlcbfiles
#
# Description:
#       For the upgrade from root user to gstd non-root user, 
#	change the ownership of the acm lockbox files from root to nsrnmc
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#

chownacmlcbfiles()
{
    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
}

#
# 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 [ ! -d "$apachelogs" ] ; then
		runcmd mkdir -p "$apachelogs"
	fi
	# 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. Please see $instlog for details"
		exit 1
	fi
}

#
# Function:
#	get_nmcuser
#
# Description:
#       Prompts for the nmc user to run apache server
#
# Arguments:
#
#       Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_NMCUSER		web server user
#	LGTO_NMCGROUP		web server group
#
getnmcusergrp()
{
    result="invalid"

    if [ $silent_install = "false" ]; then
	echo
	echo "The embedded web server inside the NMC server must run as a non-root user."
	echo "EMC recommends that you specify a user that has limited privileges and"
	echo "file access permissions. Default user name used is '$LGTO_NMCUSER'."
    fi
    # Create nsrnmc user if it does not exist
    if [ $silent_install = "false" ]; then
	    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`
	    groupname="$LGTO_NMCGROUP"
    else
	# allow silent install to use a different user
	username=`awk -F= '/LGTO_NMCUSER/ { print $2 }' "$response_file"`
	# validate the user
	if [ -z "$username" ]; then
	    # If NMC_USER is not provided, use the DEFAULT_NMCUSER
	    echo "LGTO_NMCUSER is not provided in the response file, use \"$LGTO_NMCUSER\" ..." >> "$instlog"
	    valid_user_group "$LGTO_NMCUSER"
	    if [ "$result" != "valid" ]; then
		create_nmcuser "$LGTO_NMCUSER"
	    fi
	    username="$LGTO_NMCUSER"
	    LGTO_NMCGROUP=`groups $LGTO_NMCUSER | cut -d ":" -f 2 | cut -d " " -f 2`
	    groupname="$LGTO_NMCGROUP"
	fi
	if [ "$username" = "root" ] ; then
	    echo
	    echo "ERROR: User name cannot be root"
	    exit 1
	fi
	valid_user_group "$username"
	if [ "$result" = "valid" ]; then
	    LGTO_NMCUSER="$username"
	    LGTO_NMCGROUP=`groups $LGTO_NMCUSER | cut -d ":" -f 2 | cut -d " " -f 2`
	    groupname="$LGTO_NMCGROUP"
	    echo
	    echo "Using '$username' as the user name and '$groupname' as the group name"
	else
	    echo "ERROR: $username is not a valid OS user"
	    exit 1
	fi
    fi
}

#
# Function:
#       gethttpscertkey
#
# Description:
#       Asks the user if user wants to use existing certificae or create new.
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#
gethttpscertkey()
{
    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
    echo
    while true; do
        if [ $silent_install = "false" ]; then
            if [[ ($install_type -eq 2) ]]; then
                while true ; do
                    ask "Do you want to create new(cn) certificate or use existing(ue) certificate" "ue" "?"
                    if [[ (`expr match cn $result` -ne 0) || (`expr match CN $result` -ne 0) ||
			  (`expr match cN $result` -ne 0) || (`expr match Cn $result` -ne 0)]]; then
                        result=cn
                        break
                    elif [[ (`expr match ue $result` -ne 0) || (`expr match UE $result` -ne 0) ||
			    (`expr match uE $result` -ne 0) || (`expr match Ue $result` -ne 0)]]; then
                        result=ue
                        break
                    else
                        echo "Please respond \`cn\` for create new certificate or \`ue\` for using existing certificate."
                    fi
                done
                if [ $result = "cn" ]; then
                    createcert
                elif [ $result = "ue" ]; then
                    useexistcert
                fi
            elif [[ ($install_type -eq 0) || ($install_type -eq 1) ]]; then
                while true ; do
                    ask "Do you want to create new(cn) certificate or use existing(ue) certificate" "cn" "?"
                    if [[ (`expr match cn $result` -ne 0) || (`expr match CN $result` -ne 0) ||
			  (`expr match cN $result` -ne 0) || (`expr match Cn $result` -ne 0)]]; then
                        result=cn
                        break
                    elif [[ (`expr match ue $result` -ne 0) || (`expr match UE $result` -ne 0) ||
			    (`expr match uE $result` -ne 0) || (`expr match Ue $result` -ne 0)]]; then
                        result=ue
                        break
                    else
                        echo "Please respond \`cn\` for create new certificate or \`ue\` for using existing certificate."
                    fi
                done
                if [ $result = "cn" ]; then
                    createcert
                elif [ $result = "ue" ]; then
                    useexistcert
                fi
            fi
            break
        else
            use_exist_cert=`awk -F= '/LGTO_USEEXISTCERT/ { print $2 }' "$response_file"`
            cert_file=`awk -F= '/LGTO_HTTPSCERT/ {print $2 }' "$response_file"`
            key_file=`awk -F= '/LGTO_HTTPSKEY/ {print $2 }' "$response_file"`
            if [[ ($use_exist_cert = "y") && (-f $cert_file) && (-f $key_file) ]]; then
                validatecert
		if [ $error_number -ne 0 ]; then
		    echo "Hence creating new certificate and key for https configuration."
		    createcert
		fi
	    elif [[ ($use_exist_cert = "y") && (! -f $cert_file) ]]; then
		echo "Certificate file \"$cert_file\" is not found. Creating new certificate & key for https configuration."
		createcert
	    elif [[ ($use_exist_cert = "y") && (! -f $key_file) ]]; then
		echo "Key file \"$key_file\" is not found. Creating new certificate & key for https configuration."
		createcert
            elif [[ (-z $use_exist_cert) || ($use_exist_cert = "n") ]]; then
                createcert
            fi
            break
        fi
    done
}

#
# Function:
#       useexistcert
#
# Description:
#       Prompts the user for certificate and key file for https configuration.
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#
useexistcert()
{
    use_exist_cert="true"
    count=-1
    while [ $count -le 2 ]; do
	let "count=count+1"
	if [ $count -eq 2 ]; then
	    echo
	    echo "NOTE: Reached maximum attempts to provide a valid certificate file & key file."
	    echo "Creating new certificate & key file for https configuration."
	    echo
	    createcert
	    break
	fi
        if [ $silent_install = "false" ]; then
            if [ ! -f "$cert_file" ]; then
                echo
                validfile "Specify the path of certificate file for https configuration :" "Certificate file"
                cert_file=$result
                validfile "Specify the path of key file for https configuration :" "Key file"
                key_file=$result
                validatecert
                if [ $error_number -ne 0 ]; then
		    cert_file=
		    key_file=
                    continue
                else
                    break
                fi
            else
                echo
                yesno "Do you want to use \"$cert_file\" certificate file & \"$key_file\" key file" "y"
                if [ $result = "y" ]; then
                    validatecert
                    if [ $error_number -ne 0 ]; then
			cert_file=
			key_file=
                        continue
                    else
                        break
                    fi
                else
                    validfile "Specify the path of certificate file for https configuration :" "Certificate file"
                    cert_file=$result
                    validfile "Specify the path of key file for https configuration :" "Key file"
                    key_file=$result
                    validatecert
                    if [ $error_number -ne 0 ]; then
			cert_file=
			key_file=
                        continue
                    else
                        break
                    fi
                fi
            fi
        fi
    done
}

#
# 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."
    echo
    runcmd $gstconfig -c
    valid_cert="true"
}

#
# Function:
#       validfile
#
# Description:
#       Checks validity of a file
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#       $1                      The prompt string to display.
#       $2                      Type of file
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#
validfile()
{
    while true; do
        ask "$1"
	result=`sed -e 's/^"//' -e 's/"$//' <<< "$result"`
        if [ -z $result ]; then
            echo
            echo "$2 cannot be empty."
            echo
            continue
        else
            if [ -f $result ]; then
                break
            else
                echo
                echo "$2 \"$result\" does not exist."
                echo
                continue
            fi
        fi
    done
}

#
# Function:
#       validatecert
#
# Description:
#       Valiates the certificate file.
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#
#       Return Variable         Purpose
#       ----------------------  --------------------------------------------
#
validatecert()
{
    valid_cert="false"
    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" = "no") && ("$usekey" = "no") ]]; then
        echo
        echo "ERROR: Certificate file & key file should have read permissions for other users."
    elif [ "$usecert" = "no" ]; then
        echo
        echo "ERROR: Certificate file should have read permissions for other users."
    elif [ "$usekey" = "no" ]; then
        echo
        echo "ERROR: Key file should have read permissions for other users."
    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
            echo "Successfully validated certificate & key file."
            echo "Note: Using existing certificate \"$cert_file\" & key file \"$key_file\" for https configuration."
            echo
            valid_cert="true"
        elif [ $error_number -eq 2 ]; then
            echo
            echo "ERROR: NMC HTTPS configuration does not support SHA1 based certificate."
            echo
        elif [ $error_number -eq 3 ]; then
            echo
            echo "ERROR: Key file \"$key_file\" does not correspond to certificate file \"$cert_file\"."
            echo
        else
            echo
            echo "ERROR: $cert_file is not a valid certificate."
        fi
    elif [[ ("$usecert" = "no") || ("$usekey" = "no") ]]; then
        error_number=-1
    fi
}

#
# Function:
#       readhttpsconf
#
# Description:
#       Reads the .https.conf file.
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#	Exits if httpd.conf is corrupted
#
readhttpsconf()
{
    runcmd $gstconfig -r
    if [ $? -ne 0 ]; then
        echo
        echo "File \"$apacheconf\" is corrupted. Hence exiting..."
        echo
        exit
    fi

    # Read the install type from .https.conf
    #if [ -f $httpsconfig ]; then
	#error_number=$(grep errorno $httpsconfig | cut -d' ' -f2)
    #fi
}
#
# Function:
#       checkSocketStatsCmd
#
# Description:
#       check for socket statistics command
#
# Arguments:
#
#       Parameter               Purpose
#       ----------------------  --------------------------------------------
#
# Returns:
#       Exits if socket stats command netstat/ss not installed
#
checkSocketStatsCmd()
{
  	if ! `which netstat &> /dev/null` ; then
            
		if  ! `which ss &> /dev/null` ; then
		        echo ""
	        	echo "	Warning !! netstat/ss command utility not found"
	        	echo ""
	        	exit 1;
		fi
        	
        fi
}

# Function:
#	getwebport
#
# Description:
#	Prompts for the web server port.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_HTTPPORT		web server port
#
getwebport()
{
    # get embedded web server port
    if [ $silent_install = "true" ]; then
	DEFAULT_BASEPORT=`awk -F= '/LGTO_HTTPPORT/ { print $2 }' "$response_file"`
    fi
    # Set default value if not set already
    if [ "X$DEFAULT_BASEPORT" = "X" ]; then
	DEFAULT_BASEPORT=9000
    fi
    validport "Specify the port that the web server should use for communication" $DEFAULT_BASEPORT 0 1
    LGTO_HTTPPORT="$result"
}

#
# Function:
#	getdbport
#
# Description:
#	Gets for the database  server port.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_DBSRVPORT		database server port
#
getdbport()
{
    if [ $silent_install = "true" ]; then
	 DEFAULT_DBSRVPORT=`awk -F= '/LGTO_DBSRVPORT/ { print $2 }' "$response_file"`
    fi
    if [ "X$DEFAULT_DBSRVPORT" = "X" ]; then
	DEFAULT_DBSRVPORT=5432
    else
	if [ "$DEFAULT_DBSRVPORT" = "2638" ]; then
	    DEFAULT_DBSRVPORT=5432
	fi
    fi
    use_default_port=1
    while true; do
	validport "Specify the port that the database server should use for communication" $DEFAULT_DBSRVPORT 0 $use_default_port
	use_default_port=0
	if [ $result -eq $LGTO_HTTPPORT ]; then
	    echo
	    echo "ERROR: Web server and database server port numbers cannot be the same"
	    if [ $silent_install = "true" ]; then
		exit 1
	    fi
	    continue
	fi
	if [ $result -eq $LGTO_GSTPORT ]; then
	    echo
	    echo "ERROR: GST server and database server port numbers cannot be the same"
	    if [ $silent_install = "true" ]; then
		exit 1
	    fi
	    continue
	fi

	LGTO_DBSRVPORT=${result}
	break
    done
}

#
# Function:
#	getgstport
#
# Description:
#	Prompts for the GST server port.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_GSTPORT		GST server port
#
getgstport()
{
    # get GST server port
    # Set default value if not set already
    if [ $silent_install = "true" ]; then
	 DEFAULT_GSTPORT=`awk -F= '/LGTO_GSTPORT/ { print $2 }' "$response_file"`
    fi
    if [ "X$DEFAULT_GSTPORT" = "X" ]; then
	DEFAULT_GSTPORT=`expr $LGTO_HTTPPORT + 1`
	# Make sure default port is in valid range
	if [ $DEFAULT_GSTPORT -gt 49151 ]; then
	    DEFAULT_GSTPORT=9001
	fi
    fi
    use_default_port=1
    while true; do
	validport "Specify the port the GST server should use for communication" $DEFAULT_GSTPORT 0 $use_default_port
	use_default_port=0
	if [ $result -eq $LGTO_HTTPPORT ]; then
	    echo
	    echo "ERROR: Web server and GST server port numbers cannot be the same"
	    if [ $silent_install = "true" ]; then
		exit 1
	    fi
	else
	    LGTO_GSTPORT="$result"
	    break
	fi
    done
}

getpid()
{
	if [ -x /usr/bin/ps ] ; then
		/usr/bin/ps -e | awk "/$1\$/ {print \$1}"
	else
		/bin/ps -e | awk "/$1\$/ {print \$1}"
	fi
}

#
# Function:
#	killproc
#
# Description:
#	Kills a process and then waits for 20 sec for it to die.
#	Tries to kill 10 times, returns 1 if failed
#
# Arguments:
#
#	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	0 - success
#	1 - failed
#
# Notes:
#
killproc()
{
	pid=$1
	loop_count=10
	loop_index=0
	result=1
	kill -TERM $pid
	while [ $loop_index -lt $loop_count ]; do
		pid=`getpid dbsrv9`
		if [ -n "$pid" ]; then
			echo "Waiting for process ($pid) to exit gracefully"
			sleep 20
			loop_index=`expr $loop_index + 1`
		else
			result=0
			break
		fi
	done;
}

#
# Function:
#	checkmigration
#
# Description:
#	Checks if database migration is needed from previous install.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_MIGRATIONDIR
#
checkmigration()
{
    LGTO_DBUSER=$LGTO_NMCUSER
    # Show initial defaults based on the presence of the unload tag file
    if [ -f ${gstlogs}/dbunloaded.tag ]; then
	# The tag file contains the path of the unload dir
	DEFAULT_MIGDIRPATH=`awk 'NR == 1' ${gstlogs}/dbunloaded.tag`
	if [ -n "$DEFAULT_MIGDIRPATH" -a -f "$DEFAULT_MIGDIRPATH"/reload.sql ]; then
	    migdir="$DEFAULT_MIGDIRPATH"
	    DEFAULT_MIGRATION_VALUE="y"
	else
	    DEFAULT_MIGRATION_VALUE="n"
	fi

    else
	DEFAULT_MIGRATION_VALUE="n"
    fi
    yesno "Do you want to migrate the NMC server data from a previous ${PKG} 8.x.x release" $DEFAULT_MIGRATION_VALUE
    if [ $result = "y" ] ; then
	while true ; do
	    validdir "Specify the directory that contains the unloaded data" $migdir
	    migdir="$result"
	    if [ ! -f "$migdir/reload.sql" ]; then
		echo "$migdir does not contain the reload.sql file"
		migdir=
		continue
	    fi
	    # If postgres user already exists, check for permission
	    if [ "$LGTO_CREATEDBUSER" != "Y" ] ; then
		checkaccess $LGTO_DBUSER "$migdir"
		if [ $result != "yes" ]; then
		    echo
		    echo "ERROR: Database user \"$LGTO_DBUSER\" does not have permission to access $migdir."
		    echo "Verify that all directory components have execute permission for this user."
		    continue
		fi
	    fi
	    LGTO_MIGRATIONDIR="$migdir"
	    break
	done
    fi

}


#
# Function:
#	checkaccess
#
# Description:
#	Checks if given user has access to a specified directory
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#	$1			username whose access needs to be checked
#	$2			path to check access of
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	result
#
checkaccess()
{
    username=$1
    pathtocheck=$2

    echo "Running su to check user access" >> "$instlog"
    su - $username -s /bin/sh -c "[[ -x \"$pathtocheck\" ]]" >> "$instlog" 2>&1
    if [ $? -eq 0 ]; then
	result="yes"
    else
	result="no"
    fi
}

#
# Function:
# 	validatedbspace
#
# Description:
#	Checks if $1 has enough space to hold $2
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	$result			yes/no
validatespace()
{
    dfdir="$1"
    dudir="$2"
    size_used=`du -sk $dudir | awk '{print $1}'`
    # Go upto two levels up if specified dir is not present
    if [ ! -d $dfdir ]; then
	parentdir=`dirname "$dfdir"`
        dfdir=$parentdir
    fi
    if [ ! -d $dfdir ]; then
	parentdir=`dirname "$dfdir"`
        dfdir=$parentdir
    fi
    if [  -d $dfdir ]; then
	size_avlbl=`df -lk $dfdir | sed -n '2,$p' | sed -e 's/\([^ ]* *[^ ]* *[^ ]* *\)\([^ ]*\).*/\2/' | sed -n '/./p'`
	declare -i diff_size
	diff_size="$size_avlbl - $size_used"
	if [ $diff_size -lt 0 ] ; then
	    result="no"
	else
	    result="yes"
	fi
    else
	echo "$dfdir is not a valid directory"
	result="no"
    fi
}


#
# Function:
#	getdbdir
#
# Description:
#	Prompts for the database directory.
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_DATADIR
#	LGTO_OVERWRITE
#
getdbdir()
{
    # get database dir
    # Set default value if not set already
    if [ $silent_install = "true" ]; then
	gstdbdir=`awk -F= '/LGTO_DATADIR/ { print $2 }' "$response_file"`
	overwritedb=`awk -F= '/LGTO_OVERWRITE/ { print $2 }' "$response_file"`
	if [ -n "$gstdbdir" ]; then
	    DEFAULT_DBDIR="$gstdbdir"
	fi
	if [ -n "$overwritedb" ]; then
	    LGTO_OVERWRITE="$overwritedb"
	else
	    LGTO_OVERWRITE="N"
	fi
    fi
    if [ "X$DEFAULT_DBDIR" = "X" ]; then
   	DEFAULT_DBDIR="/nsr/nmc/nmcdb"
    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
    fi
    # flag to make sure was ask for migration only once
    asked_for_migration=false
    while true ; do

	validdir "Specify the directory to use for the ${PKG} database" "$DEFAULT_DBDIR"
	datadir="$result"
	is_ascii_path "$datadir"
	if [ "$result" = "n" ]; then
	    echo
	    echo "ERROR: The path contains invalid characters: $result_temp_path"
	    if [ $silent_install = "true" ]; then
		exit 1
	    fi
	    continue
	fi

	if [ $silent_install = "true" ]; then
	    # Assuming no migration needed for silent install
	    LGTO_DBUSER=$LGTO_NMCUSER
	    if [ -d "$datadir/$DBNAME" ]; then
		echo "Changing the ownership of $datadir to $LGTO_NMCUSER" >>  "$instlog" 2>&1
                chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$datadir" >>  "$instlog" 2>&1
                if [ $? -ne 0 ] ; then
                    echo "Could not change owner of $datadir to $LGTO_NMCUSER"
                    exit 1
                fi

		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
	    fi
	    break
	fi

	parent=`dirname "$datadir"`
	if [ -d "$parent" ] ; then
	    #check if database exists
	    if [ -d "$datadir/$DBNAME" ]; then
		yesno "A database already exists in $datadir, do you want to retain this database" y
		if [ "$result" = "y" ]; then
		    while true ; do
			# 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"
                            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"
			    break
			fi
			if [ "$DBOWNER" = "root" ]; then
			    echo
		     	    echo "ERROR: $datadir is owned by root"
			    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
			if [ "$DBOWNER" = "$LGTO_DBUSER" ]; then
			    break
			fi
			echo
			echo "ERROR: The database at ${datadir}/${DBSUBDIR} is owned by user '$DBOWNER'. This does not match"
			echo "       user name '$LGTO_DBUSER' specified earlier as the database user".

			valid_user_group "$DBOWNER"
			if [ "$result" = "valid" ]; then
			    yesno "Use '$DBOWNER' as the database user" y
			    if [ "$result" = "y" ]; then
	    			LGTO_DBUSER="$DBOWNER"
				LGTO_CREATEDBUSER="N"
				break
			    else
				DBOWNER="invalid_db_owner"
				break
			    fi
			else
			    echo
			    echo "ERROR: '$DBOWNER' is not a valid user. Fix the permissions of ${datadir}/${DBSUBDIR} and"
			    echo "run the script again."
			    exit 1
			fi
		    done

		    if [ "X$DBOWNER" = "Xinvalid_db_owner" ]; then
			continue
		    else
		        LGTO_OVERWRITE="N"
		        break
		    fi
		else
		    # check if database exists
		    if [ -d "$datadir/$DBNAME" ] ; then
			yesno "$datadir already exists, is it okay to remove it" n
			if [ "$result" = "y" ] ; then
			    # We will remove the log file also if present
			    LGTO_OVERWRITE="Y"
			    break
			fi
		    fi
		fi
	    else
		if [  -d "$datadir" ]; then
		    if [ ! -z "$(ls -A $datadir)" ] ; then
			echo "ERROR: $datadir is not empty. Database directory should be an empty directory"
			continue
		    fi
		fi
		if [ $asked_for_migration = "false" ] ; then
		    checkmigration
		    asked_for_migration="true"
		fi
		# Validate space if migration is needed
		if [ "X$LGTO_MIGRATIONDIR" != "X" ] ; then
		    validatespace $datadir $LGTO_MIGRATIONDIR
		    if [ $result = "no" ] ; then
			echo "ERROR: $datadir does not have enough space to migrate data from $LGTO_MIGRATIONDIR"
			continue
		    fi
		fi
		break
	    fi
	else
	    if [ $asked_for_migration = "false" ] ; then
		checkmigration
		asked_for_migration="true"
	    fi
	    # Validate space if migration is needed
	    if [ "X$LGTO_MIGRATIONDIR" != "X" ] ; then
		validatespace $datadir $LGTO_MIGRATIONDIR
		if [ $result = "no" ] ; then
		     echo "ERROR: $datadir does not have enough space to migrate data from $LGTO_MIGRATIONDIR"
		     continue
		fi
	    fi
	    # Do not prompt for parent directory creation if using default path
	    if [ "$parent" = "/nsr/nmc" ]; then
		break
	    fi
	    yesno "Parent directory $parent does not exist, should it be created" y
	    if [ "$result" = "y" ] ; then
		break
	    fi
	fi
    done
    LGTO_DATADIR="$datadir"
}


#
# Function:
#	getnsrdir
#
# Description:
#
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_NSRDIR
#
getnsrdir()
{
    DEFAULT_NSRDIR="$nsrbase/sbin"

    if [ $silent_install = "true" ]; then
	nsrdir=`awk -F= '/LGTO_NSRDIR/ { print $2 }' "$response_file"`
	if [ -n "$nsrdir" ]; then
	    DEFAULT_NSRDIR="$nsrdir"
	fi
    else
	# If the default one works, do not ask for non silent install
	if [ -f "$DEFAULT_NSRDIR/nsrexecd" ]; then
	    LGTO_NSRDIR="$DEFAULT_NSRDIR"
	    return
	fi
    fi

    # get NetWorker directory
    while true ; do
	validdir "Specify where the NetWorker binaries are installed" "$DEFAULT_NSRDIR" "yes"
	if [ -f "${result}/nsrexecd" ] ; then
	    break
	else
	    echo
	    echo "ERROR: nsrexecd(1m) is not present in ${result}! Please re-enter."
	    if [ $silent_install = "true" ]; then
		exit 1
	    fi
	fi
    done
    LGTO_NSRDIR="$result"
}


#
# Function:
#	getauthhostport
#
# Description:
#
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_AUTHHOST
#	LGTO_AUTHPORT
#
getauthhostport()
{    
    #if authc package is installed and we do not have default authhost, use local machine
    if [ "$authc_installed" == "true" ]; then
	if [ -z "$DEFAULT_AUTHHOST" ]; then
	    DEFAULT_AUTHHOST=`hostname`
	fi
	if [ -z "$DEFAULT_AUTHPORT" ]; then
	    if [ -f "/opt/nsr/authc-server/conf/authc-server-app.json" ]; then
		USINGDEFAUTHCPORT=`cat "/opt/nsr/authc-server/conf/authc-server-app.json" | grep "port" | grep "9090"`
		if [ -n "$USINGDEFAUTHCPORT" ]; then
		    DEFAULT_AUTHPORT="9090"
		fi
	    fi
	fi
    fi
    while true ; do

	silent_install_processed="false"
	while true; do
	    if [ $silent_install = "false" ]; then
		ask "Specify the host name of the NetWorker Authentication Service host" "$DEFAULT_AUTHHOST" ":"
	    else
		if [ "$silent_install_processed" = "false"  ]; then
		    silent_install_processed="true";
		    result=`awk -F= '/LGTO_AUTHHOST/ { print $2 }' "$response_file"`
		else
		    exit 1
		fi
	    fi

	    if [ -z "$result" ]; then
		echo "ERROR: A valid host name of the authentication server is required."
		if [ $silent_install = "false" ]; then
		    continue
		else
		    exit 1
		fi
	    else
		LGTO_AUTHHOST="$result"
	    fi
	    break
	done

	silent_install_processed="false"
	while true; do
	    if [ $silent_install = "false" ]; then
		if [ -z "$DEFAULT_AUTHPORT" ]; then
		    DEFAULT_AUTHPORT="9090"
		else
		    #If default port is present, try it first without asking
		    LGTO_AUTHPORT=$DEFAULT_AUTHPORT
		    DEFAULT_AUTHPORT=
		    break
		fi

		ask "Specify the port number that the NetWorker Authentication Service uses for communication" "$DEFAULT_AUTHPORT" ":"
	    else
		if [ "$silent_install_processed" = "false"  ]; then
		    silent_install_processed="true";
		    result=`awk -F= '/LGTO_AUTHPORT/ { print $2 }' "$response_file"`
		else
		    exit 1
		fi
	    fi

	    if [ -z "$result" ]; then
		echo "ERROR: A valid port number of the authentication server is required."
		if [ $silent_install = "false" ]; then
		    continue
		else
		    exit 1
		fi
	    else
		LGTO_AUTHPORT="$result"
		DEFAULT_AUTHPORT=
	    fi
	    break
	done

	#if both host and port are specified, test connection
	if [ $silent_install = "false" -a ! -z "$LGTO_AUTHHOST" -a ! -z "$LGTO_AUTHPORT" ]; then

	    #Check if authc host is local host, if yes, validate that NW services are up
	    if [ $NETWORKER_STARTED = "false" ]; then
		SHORTCURHOST=`hostname | cut -d "." -f 1`
		SHORTAUTHCHOST=`echo $LGTO_AUTHHOST | cut -d "." -f 1`
		if [ ! -z "$SHORTCURHOST" -a ! -z "$SHORTAUTHCHOST" ]; then
		    if [ "$SHORTCURHOST" = "$SHORTAUTHCHOST" -o "$SHORTAUTHCHOST" = "localhost" ]; then
			pid=`getpid nsrexecd`
			if [ -z "$pid" ]; then
			    echo
			    echo "WARNING: NetWorker services are not running on this host. To validate the"
			    echo "authentication server on host $LGTO_AUTHHOST, NetWorker services on"
			    echo "this host must be started now."
			    yesno "Do you want to start NetWorker services now" "y"
			    if [ "$result" = "y" ]; then
                                 if [[ ("$ARCH" == "Linux") && ("$INIT_SYSTEM" == "systemd") ]]; then
				  systemctl start networker.service
				 else
				  /etc/init.d/networker start
				 fi
				sleep 5
				NETWORKER_STARTED="true"
			    fi
			fi
		    fi
		fi
	    fi

	    while true; do
		AUTHC_RUNNING="false"
		"$gstauthcfg" -h "$LGTO_AUTHHOST" -p "$LGTO_AUTHPORT" -t  >> "$instlog" 2>&1
		if [ $? -ne 0 ] ; then
		    echo
		    echo "WARNING: Unable to contact authentication server on host $LGTO_AUTHHOST and port $LGTO_AUTHPORT"
		    #If NW services were started recently, give option to retry
		    if [ $NETWORKER_STARTED = "true" ]; then
			echo
			echo "It might take a few seconds for NetWorker services to start if they"
			echo "were started recently."
			yesno "Do you want to test the connection again" y
			if [ "$result" = "y" ] ; then
			    continue
			else
			    break
			fi
		    else
			break
		    fi

		else
		    AUTHC_RUNNING="true";
		    break
		fi
	    done

	    if [ $AUTHC_RUNNING = "false" ]; then
		yesno "Do you want to specify a different authentication server host or port" y
		if [ "$result" = "y" ] ; then
		    continue
		fi
	    fi
	fi
	break

    done
}

#
# Function:
#	getbootval
#
# Description:
#
#
# Arguments:
#
# 	Parameter		Purpose
#	----------------------	--------------------------------------------
#
# Returns:
#
#	Return Variable		Purpose
#	----------------------	--------------------------------------------
#	LGTO_KEEPBOOT
#
getbootval()
{
    if [ $silent_install = "true" ]; then
	bootval=`awk -F= '/LGTO_KEEPBOOT/ { print $2 }' "$response_file"`
	if [ -n "$bootval" ]; then
	   result="$bootval"
	else
	   result="n"
	fi
    else
	pid=`getpid nsrexecd`
	if [ -z "$pid" ]; then
	    yesno "Start the NMC server daemons at end of the configuration" n
	else
	    yesno "Start the NMC server daemons at end of the configuration" y
	fi
    fi
    LGTO_KEEPBOOT="$result"
}


#
# main
#
PATH="/bin:/usr/bin:/sbin:/usr/sbin:$PATH"
export PATH
ARCH=`uname`
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"

if  `which lsb_release &> /dev/null` ; then
    OS_DIST=$(lsb_release -d | cut -d' ' -f1 | cut -f2)
else
    OS_DIST=`grep DISTRIB_ID /etc/*-release | awk -F '=' '{print $2}' 2> /dev/null`
fi
UBUNTU="Ubuntu"
case "$ARCH" in
    Linux )
	    if [ "$OS_DIST" == "$UBUNTU" ]; then
		# For Debian (Ubuntu), Prefix option is not supported
		# Hardcode the default path
		base=/opt/lgtonmc
		nsrbase=/usr
		if [ ! -f "$base/bin/gstd" ]; then
                        echo "ERROR: Unable to get install directory. File $base/bin/gstd not found."
                        exit 1
                fi
	    else
		base=`rpm -q --qf "%{INSTPREFIXES}\n" lgtonmc 2> /dev/null`
		if [ ! -f "$base/bin/gstd" ]; then
		    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
		fi
		nsrbase=`rpm -q --qf "%{INSTPREFIXES}\n" lgtoclnt 2> /dev/null`
		if [ ! -f "$nsrbase/sbin/nsrexecd" ]; then
		    nsrbase="/usr"
		fi
	    fi
	    ;;
esac
rm -rf "${base}/postgres_latest"
ln -sf "${base}/postgres/16.8" "${base}/postgres_latest"
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"

silent_install="false"
umask 0022

# check if the script needs to run in silent mode
if [ ! -z "$1" ]; then
    if [ "$1" != "-silent" -o  -z "$2" -o ! -f "$2" ]; then
        echo "usage: $0 [-silent response_file]"
        exit 1
    fi
    silent_install="true"
    response_file="$2"
fi


# stop any existing GST server
case "$ARCH" in
    Linux )
	    pkill gstd
	    ;;
esac

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

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

checkforupgrade

# Check status of NW services and ask user if they want to start it
if [ $silent_install = "false" ]; then
    pid=`getpid nsrexecd`
    if [ -z "$pid" ]; then
	yesno "NetWorker services on this host are not running. Do you want to start them now" "y"
	if [ "$result" = "y" ]; then
        if [[ ("$ARCH" == "Linux") && ("$INIT_SYSTEM" == "systemd") ]]; then
	  systemctl start networker.service
	  NETWORKER_STARTED="true"
	else
	  /etc/init.d/networker start
	  NETWORKER_STARTED="true"
	  fi
	fi
    fi
fi

getnmcusergrp
chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$gstlogs"
chown -R "$LGTO_NMCUSER":"$LGTO_NMCUSER" "$apachelogs"

authc_installed=false
    if [ "$OS_DIST" == "$UBUNTU" ]; then
	status=`dpkg-query --show --showformat='${db:Status-Status}\n' lgtoauthc 2> /dev/null`
	if [ "$status" == "installed" ]; then
	    authc_installed=true
	fi
    else
	rpm -q lgtoauthc > /dev/null 2>&1
	if [ $? -eq 0 ]; then
	    authc_installed=true
	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

# Read .https.conf file and figure out the install type
readhttpsconf

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)
else
    echo
    echo "Please refer install log $instlog for more information."
    echo
fi

checkSocketStatsCmd
# Get the certificate & key fle path for apache https configuration
gethttpscertkey
getwebport
getgstport
getdbport
getdbdir
getauthhostport
getnsrdir
getbootval

cat <<EOF

Creating the installation log in ${instlog}.

Performing initialization. Please wait...

EOF

# Insert install date in logfile
echo "  " >> "$instlog"
echo "Install begins `date`" >> "$instlog"
echo "  " >> "$instlog"

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

#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"
    exit 1
fi

if [ "$LGTO_CREATEDBUSER" = "Y" ] ; then
   # make sure parent dir is present as useradd on Redhat creates user's home dir (our db dir)
   # and will fail if parend dir is not present
   parentdir=`dirname "$LGTO_DATADIR"`
   if [ ! -d "$parentdir" ]; then
	echo "Creating directory $parentdir" >> "$instlog"
	mkdir -p "$parentdir" >> "$instlog" 2>&1
	if [ $? -ne 0 ] ; then
	    echo "Could not create $parentdir"
	    exit 1
	fi
    fi
    echo "Creating user $LGTO_DBUSER"  >> "$instlog"
    #Create user account without specifying password so that it is locked by default
    if [ -f /sbin/nologin ]; then
	useradd -s /sbin/nologin -d "$LGTO_DATADIR" "$LGTO_DBUSER" >> "$instlog" 2>&1
    else
	if [ -f /usr/sbin/nologin ]; then
	    useradd -s /usr/sbin/nologin -d "$LGTO_DATADIR" "$LGTO_DBUSER" >> "$instlog" 2>&1
	else
	    useradd -d "$LGTO_DATADIR"  "$LGTO_DBUSER" >> "$instlog" 2>&1
	fi
    fi
    myerrval=$?
    if [ $myerrval -ne 0 ] ; then
        echo "ERROR: Could not create user $LGTO_DBUSER. Error:$myerrval" >> "$instlog"
        if [ $myerrval -eq 9 ] ; then
            echo "ERROR: $LGTO_DBUSER user already in use, Please specify other username for the database server."
        else
            echo "ERROR: Could not create user $LGTO_DBUSER. Please see $instlog for details."
        fi
        exit 1
    fi
    # Validate privileges if migration is required
    if [ "X$LGTO_MIGRATIONDIR" != "X" ] ; then
	while true ; do
	    checkaccess $LGTO_DBUSER "$LGTO_MIGRATIONDIR"
	    if [ $result != "yes" ]; then
		echo "ERROR: Database user \"$LGTO_DBUSER\" does not have permission to access $LGTO_MIGRATIONDIR."
		echo "Verify that all directory components have execute permission for this user."
		echo
	        echo "Fix the permissions of the directory components in the path and press enter."
		echo
		read ans
		continue
	    fi
	    break
	done
    fi
fi

# create database
if [ "$LGTO_OVERWRITE" = "Y" ] ; then
    if [ -d "$LGTO_DATADIR/pgdata" ]; then
	echo "Removing $LGTO_DATADIR/" >> "$instlog"
	rm -rf "$LGTO_DATADIR/pgdata" >> "$instlog" 2>&1
	rm -rf "$LGTO_DATADIR/gstd_db.conf" >> "$instlog" 2>&1
	rm -rf "$LGTO_DATADIR/db_output.log" >> "$instlog" 2>&1
	# Delete any .rc files if home dir was created by useradd
	rm -rf "$LGTO_DATADIR"/.??* >> "$instlog" 2>&1
    	if [ ! -z "$(ls -A $LGTO_DATADIR)" ] ; then
	    echo "Directory $LGTO_DATADIR contains non database files"
	    exit 1
	fi
    fi
fi

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"
	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"
	exit 1
    fi
    chmod 700 "$LGTO_DATADIR" >> "$instlog" 2>&1
    if [ $? -ne 0 ] ; then
	echo "Could not change permissions of $LGTO_DATADIR"
	exit 1
    fi
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

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

    #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 "Migration to Postgres $postgreslatestversion 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"
        echo "See install.log and pg_upgrade_*.log in logs directory for more details."
        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"
    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"
        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"
    	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"
        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"
	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"
	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 rm -f /etc/init.d/gst
        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 [ "$OS_DIST" == "$UBUNTU" ]; then
	    # Replace the existing file if present
	    runcmd ln -sf /opt/lgtonmc/etc/gst.service /lib/systemd/system/
	 else
	    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/
	 fi
	 runcmd systemctl --no-reload disable gst.service > /dev/null 2>&1
	 runcmd systemctl enable gst.service > /dev/null 2>&1
         runcmd 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"

# Create  the database
echo "** Create the database in $LGTO_DATADIR **" >> "$instlog"
if [ "$LGTO_OVERWRITE" != "N" ] ; then
    # Set owner again, in case the postgres user was different before
    chown $LGTO_DBUSER "$LGTO_DATADIR" >> "$instlog" 2>&1
    if [ $? -ne 0 ] ; then
	echo "Could not change owner of $LGTO_DATADIR to $LGTO_DBUSER"
	exit 1
    fi
    runcmd "$gstdbinit" -U "$LGTO_DBUSER" -n "$LGTO_DBSRVPORT" "$LGTO_DATADIR"

fi

LGTO_MIGRERROR="n"
# Migrate data if needed
if [ "X$LGTO_MIGRATIONDIR" != "X" ] ; then
    echo "Starting migration of data from $LGTO_MIGRATIONDIR to $LGTO_DATADIR"
    echo "and logging output to $instlog. Please wait..."
    echo "Starting migration of data from $LGTO_MIGRATIONDIR to $LGTO_DATADIR" >> "$instlog"
    runcmd ""$dbupgr" -p "$LGTO_MIGRATIONDIR" -n "$LGTO_DATADIR" -u "$LGTO_DBUSER" "
    if [ $? -ne 0 ]; then
	LGTO_KEEPBOOT="n"
	echo "ERROR: Migration failed. Please fix errors in $instlog and run $dbupgr again."
	LGTO_MIGRERROR="y"
    fi
fi

# 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

# Start the GST server
if [ "$LGTO_KEEPBOOT" = "y" ] ; then
    echo "Starting the GST server" >> "$instlog"
    if [[ ("$ARCH" == "Linux") && ("$INIT_SYSTEM" == "systemd") ]]; then
        systemctl start gst.service
    else
        /etc/init.d/gst start
    fi
    if [ $? -ne 0 ] ; then
        echo "Warning: Failed to start the gst daemon."
        if [[ ("$ARCH" == "Linux") && ("$INIT_SYSTEM" == "systemd") ]]; then
             echo "         Start the nsrexecd daemon and then use the script /etc/systemd/system/gst.service to start the gst daemon manually."
        else
             echo "         Start the nsrexecd daemon and then use the script /etc/init.d/gst to start the gst daemon manually."
        fi
    fi
fi

if [ "LGTO_MIGRERROR" = "y" ] ; then
    echo "Installation completed with errors."
else
    if [ -f ${gstlogs}/dbunloaded.tag ]; then
	runcmd rm -f ${gstlogs}/dbunloaded.tag
    fi
    echo "The installation completed successfully."
fi

# Don't let the user run this twice...
# nmc_config file is registered as part of RPM database.
# It should not be manually deleted, in some cases uninstall of NMC throws
# warning stating 'no such file or directory'
# rm $0

exit 0
