#! /bin/sh
#
# $Id$ Copyright (c) 2018-2024 Dell Inc. or its subsidiaries. All Rights Reserved.
#

#
# Copyright (c) 2018-2024 Dell Inc. or its subsidiaries. All Rights Reserved.
#
# This software contains the intellectual property of Dell Inc.
# or is licensed to Dell Inc. from third parties. Use of this
# software and the intellectual property contained therein is
# expressly limited to the terms and conditions of the License
# Agreement under which it is provided by or on behalf of Dell
# Inc. or its subsidiaries.
#

cdir=`dirname ${0}`
ARCH=`uname`
DISTRO=`grep PRETTY_NAME /etc/os-release | cut -d'"' -f2 | cut -d' ' -f1 2> /dev/null`
if [ "$ARCH" = "Linux" ]; then
    if [ "$DISTRO" = "Ubuntu" ]; then
        base=/opt/nwui
    else
        base=`rpm -q --qf "%{INSTPREFIXES}\n" lgtonwui 2> /dev/null`
    fi
fi

if [ -z "$JSVC_DIR" ]; then
	JSVC_DIR=${base}/jsvc
fi
MS_EXEC=${JSVC_DIR}/jsvc

SYS_ENV_FILE=${base}/bin/nwuirc

if [ -f "$SYS_ENV_FILE" ]
then
	if [ -r "$SYS_ENV_FILE" ]
	then
		. "$SYS_ENV_FILE"
	else
		echo >&2 "Unable to source environment file '$SYS_ENV_FILE'."
	fi
fi

if [ -f "${cdir}/setenv.sh" ]
then
        . "${cdir}/setenv.sh"
else
        echo >&2 "Unable to source environment file '${cdir}/setenv.sh'."
fi

if [ -z "$TCHOME" ]; then
	echo 1>&2 "TCHOME is not set."
	exit 1
fi
if [ -z "$CATALINA_BASE" ]; then
	echo 1>&2 "CATALINA_BASE is not set."
	exit 1
fi
if [ -z "$TCUSER" ]; then
	echo 1>&2 "TCUSER is not set."
	exit 1
fi
if [ -z "$NWUICONF" ]; then
    echo 1>&2 "NWUICONF is not set."
    exit 1
fi
CATALINA_HOME=${TCHOME}
MS_HOME=${CATALINA_BASE}
MS_TCUSER=${TCUSER}

MS_LOG_FILE=${MS_HOME}/logs/catalina.out
MS_ERR_FILE=${MS_HOME}/logs/catalina.err
MS_PID_FILE=${MS_HOME}/nwui-tomcat.pid
MS_PROC_PATTERN="jsvc.*${MS_PID_FILE}.*org.apache.catalina.startup.Bootstrap$"
# purge old tomcat access log
(${CATALINA_HOME}/../bin/tomcat_log_purge.sh AUTHC_INIT_PURGE)
# abort if another authentication process is running
pgrep -U ${MS_TCUSER} -f ${MS_PROC_PATTERN} >/dev/null 2>&1
if [ $? -eq 0 ]; then
	pid=`pgrep -U ${MS_TCUSER} -f ${MS_PROC_PATTERN}`
	echo 1>&2 "Could not start the nwui service because another nwui service process is still running ($pid)."
	exit 1
fi
# remove stale nwui pid file
if [ -f "$MS_PID_FILE" ]; then
	rm -f $MS_PID_FILE
	echo "Stale nwui service pid file is removed."
fi

# Start service
exec ${MS_EXEC} -nodetach \
--illegal-access=permit \
-classpath ${CATALINA_HOME}/bin/bootstrap.jar:$CATALINA_HOME/bin/tomcat-juli.jar \
-java-home ${JAVA_HOME} \
-user ${MS_TCUSER} \
-pidfile ${MS_PID_FILE} \
-Dcatalina.home=${CATALINA_HOME} \
-Dcatalina.base=${CATALINA_BASE} \
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager \
-Djava.util.logging.config.file=${CATALINA_BASE}/conf/logging.properties \
-Djava.security.properties=${NWUICONF}/java.security \
-Djava.locale.providers=COMPAT \
-XX:+IgnoreUnrecognizedVMOptions \
org.apache.catalina.startup.Bootstrap
