#! /bin/sh
# $Id$ Copyright (c) 2000-2020 EMC Corporation
#

#
# Copyright (c) 2000-2020 EMC Corporation.
#
# All rights reserved.  This is an UNPUBLISHED work, and
# comprises proprietary and confidential information of EMC.
# 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.
#

# chkconfig: 35 97 03
# description: NetWorker Management Console

### BEGIN INIT INFO
# Provides:       gst
# Required-Start: networker
# Required-Stop:
# Default-Start: 3 5
# Default-Stop: 0 1 2 6
# Description:    gst
### END INIT INFO

GST_HOME=''
PUREBINDIR=''
ARCH='linux86w'
BRAND='NetWorker'
NSR_HOME=''
NMCUSER="nsrnmc"

if [ "${GST_PURE}" = "true" ] ; then
	bindir="${PUREBINDIR}"
else
	bindir="bin"
fi

if [ -n "${GST_HOME}" ] ; then
	productdir="${GST_HOME}"
else
	productdir=`/bin/csh -cf 'echo ~gst' 2>/dev/null`
fi

gstd="${productdir}/${bindir}/gstd"
code=0
stop_code=0
arg0=`basename $0`
PATH="/bin:/usr/bin:/sbin:/usr/sbin:/usr/ucb:$PATH:${productdir}/postgres_latest/bin:${productdir}/bin"
export PATH

get_db_path()
{
    gst_db_path=`awk '/current_db_dir/ { print substr($4,2,length($4)-3) }' "$GST_HOME/etc/gstd.conf"`
    if [ ! "$gst_db_path" ]; then
	gst_db_path="/opt/lgtonmc/nmcdb"
    fi
    echo "$gst_db_path"
}

getnamefrompid()
{
	pid=$1
	
	if [ -x /usr/bin/ps ] ; then
		/usr/bin/ps -e | awk "/^ *$pid/ {print \$4}"
	else
		/bin/ps -e | awk "/^ *$pid/ {print \$4}"
	fi
}

stoptrapd()
{
	trapd_pid=`getpid gstsnmptrapd`
	# On some platforms, ps will truncate name to 8 characters 
	if [ -z "$trapd_pid" ]; then
		trapd_pid=`getpid gstsnmpt`
	fi
	if [ -n "$trapd_pid" ] ; then
		if [ "$1" != "current" ]; then
		  echo "A GST snmptrapd from previous instance is still running, killing..." >&2
		fi
		kill -TERM $trapd_pid
			sleep 1
	fi
}

stopwebserver()
{
	if [ -f ${productdir}/apache/logs/httpd.pid ] ; then
		httpd_pid=`cat ${productdir}/apache/logs/httpd.pid`
		procname=`getnamefrompid $httpd_pid`
		if [ "X${procname}" = "Xhttpd" -o "X${procname}" = "Xhttpdapache" ] ; then
			if [ "$1" != "current" ]; then
			    echo "A GST web server (httpd) from previous instance is still running, killing..." >&2
			fi
			kill -TERM $httpd_pid
			sleep 3
		fi
	fi
}

stopdbserver()
{
	gst_db_path=`get_db_path`
	if [ -f "${gst_db_path}/pgdata/postmaster.pid" ] ; then
               if [ "$1" != "current" ]; then
                    echo "A GST database server (postgres) from previous instance is still running, stopping..." >&2
		fi
		pgpid=`head -n 1 $gst_db_path/pgdata/postmaster.pid`
		if [ ! -z "$pgpid" ]; then
			# Make sure this is postgres binary
			pgcmd=`ps -e $pgpid | grep postgres`
			if [ ! -z "${pgcmd}" ]; then
				kill -INT $pgpid
				loop_count=5
				loop_index=0
				while [ -f "${gst_db_path}/pgdata/postmaster.pid" ]; do
					sleep 2;
					loop_index=`expr $loop_index + 1`
					if [ $loop_index -ge $loop_count ]; then
						break;
					fi
				done;
				if [ -f "${gst_db_path}/pgdata/postmaster.pid" ] ; then
					echo "Unable to stop postgres database server (process id $pgpid)"
				else
					echo ""
				fi
			else
				 echo "Error verifying postgres server pid"
			fi
		else
			echo "Error while reading file ${gst_db_path}/pgdata/postmaster.pid"
		fi
	fi
}

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

user_exists(){
  if id -u $1 >/dev/null 2>&1; then
    echo "1"
  else
    echo "0"
  fi
}

case "$ARCH" in
	sol*|aix*)
		bsd_echo="false"
		;;
	*)
		bsd_echo="true"
		;;
esac

if [ "$bsd_echo" = "true" ] ; then
	echo_n () {
		echo -n "$*"
	}
else
	echo_n () {
		/bin/echo "${*}\c"
	}
fi
 
# environment specific variables
case "$ARCH" in
	lin*)
		# cst libraries are used for CST ldap and its internal lockbox operation.
		# cst path is required to locate dynamic library path of cst libraries (CST and internal bsafe crypto libraries).
		# It must be the first entry of LD_LIBRARY_PATH otherwise cst fails to load libraries.
		# cst comes with own bsafe library. cst bsafe library version may or may not be the same
		# version of bsafe library used by other components for the product.
		LD_LIBRARY_PATH="${productdir}/lib64/cst:${NSR_HOME}/lib/nsr/lib64:${productdir}/postgres_latest/odbc:${productdir}/${bindir}:${productdir}/apache/lib:$LD_LIBRARY_PATH"
		export LD_LIBRARY_PATH
		;;
esac

# Get PIDs of some important daemons
nsrexecd_pid=`getpid nsrexecd`
gstd_pid=`getpid gstd`

case "$1" in
    start)
	if [ -z "$nsrexecd_pid" ]; then
	    echo "ERROR: ${BRAND} client (nsrexecd) is not running" >&2
	    exit 1;
	fi
	if [ -n "$gstd_pid" ]; then
	    echo "ERROR: GST is already running!" >&2
	    exit 1;
	fi
	 stopdbserver
	`stopwebserver`
	`stoptrapd`

	echo_n "Starting GST: "
	if [ -x "$gstd" ] ; then
	    if [[ `user_exists $NMCUSER` = "1" ]]; then
		if [[ -f "/etc/init.d/functions" ]]; then
		    . /etc/init.d/functions
		    daemon --user $NMCUSER $gstd
		elif [[ -f "/etc/init.d/rc.d/functions" ]]; then
		    . /etc/init.d/rc.d/functions
		    daemon --user $NMCUSER $gstd
		elif [[ -f "/lib/lsb/init-functions" ]]; then
		    . /lib/lsb/init-functions
		    start_daemon -u $NMCUSER $gstd
		else
		    sudo -u $NMCUSER $gstd
		fi
            else
                echo "GST services are running as root user"
                $gstd
            fi
	    code=$?
	    echo "done."
	else
	    code=253
	    echo "ERROR: $gstd not found!" >&2
	fi
	;;
    stop)
	echo_n "Stopping GST: ... "
	if [ -n "$gstd_pid" ] ; then
	    if [[ -f "/etc/init.d/functions" ]]; then
		. /etc/init.d/functions
		killproc $gstd
	    elif [[ -f "/etc/init.d/rc.d/functions" ]]; then
		. /etc/init.d/rc.d/functions
		killproc $gstd
	    elif [[ -f "/lib/lsb/init-functions" ]]; then
		. /lib/lsb/init-functions
		killproc $gstd
	    else
		kill -TERM $gstd_pid
	    fi

	    if [ $? -ne 0 ]; then
		echo "ERROR: Could not kill $gstd" >&2
		exit 1
	    fi;
	
	    # wait a little bit for gstd to stop naturally
	    loop_delay=4
	    loop_count=5
	    loop_index=0
	
	    while [ -n "$gstd_pid" ]; do
		sleep $loop_delay;
		loop_index=`expr $loop_index + 1`
		if [ $loop_index -ge $loop_count ]; then
		    break;
		fi
		gstd_pid=`getpid gstd`
	    done;
	
	    # If gstd isn't down yet, print out warning and kill it.
	    gstd_pid=`getpid gstd`
	    if [ -n "$gstd_pid" ] ; then
		echo "WARNING: using kill -KILL to stop gstd" >&2
		kill -KILL $gstd_pid

		stopdbserver current

		# Stop the web server if running
		`stopwebserver` current

		# Stop trapd if running
		`stoptrapd` current
	     else
                stopdbserver current
                # Stop the web server if running
                stopwebserver current
                # Stop trapd if running
                stoptrapd current
	    fi
	    echo "done."
	    code=0
	else
	    code=254
	    echo "WARNING: $gstd not running!" >&2
	    # Stop the web server if running
	    `stopwebserver`
	    # Stop the db server if running
	    db_pid=`get_db_path`
	    if [ -f "$db_pid"/pgdata/postmaster.pid ] ; then
		stopdbserver
	    fi
	    # Stop trapd if running
	    `stoptrapd`
	fi
	;;
    restart)
	echo "Restarting GST: "
	$0 stop
	stop_code=$?
	if [ $stop_code -ne 1 ]; then
		$0 start
	else
		echo "Not restarting GST:  GST stop error"
	fi
	;;
    status)
    	gstd_pid=`getpid gstd`
    	if [ -n "$gstd_pid" ] ; then
		echo "GST is running" >&2
	else
		echo "GST is not running" >&2
	fi
	;;
    *)
	echo "usage: $arg0 { start | stop | restart | status }" >&2
	code=255
	;;
esac

exit $code
