#!/bin/sh
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# tomcat This shell script takes care of starting and stopping Tomcat
#
# chkconfig: 345 80 20
#
### BEGIN INIT INFO
# Provides: tomcat
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Default-Start:
# Default-Stop:
# Description: start and stop tomcat
# Short-Description: start and stop tomcat
### END INIT INFO
#

. /etc/rc.d/init.d/functions

NAME=tomcat
TOMCAT_HOME=/opt/$NAME
CATALINA_PID=/var/run/tomcat/$NAME.pid
TOMCAT_LOCK=/var/lock/subsys/$NAME
CATALINA_OPTS="-Xms512m -Xmx8192m -Dlog4j.configuration=file:///opt/traffic_router/conf/log4j.properties"
SHUTDOWN_TIMEOUT=10
SHUTDOWN_FORCE=true

export NAME TOMCAT_HOME CATALINA_PID TOMCAT_LOCK

start() {
    [[ -d /var/run/tomcat ]] || mkdir /var/run/tomcat
    export CATALINA_OPTS
    runuser -s /bin/bash root -c "$TOMCAT_HOME/bin/startup.sh"
	RETVAL=$?
	echo -n "Starting $NAME"
	if [ $RETVAL = 0 ]; then
		touch $TOMCAT_LOCK
		echo_success
	else
		echo_failure	
	fi	
	echo
}


stop() {
	SHUTDOWN_OPTS="$SHUTDOWN_TIMEOUT"
	[[ $SHUTDOWN_FORCE == "true" ]] && SHUTDOWN_OPTS="$SHUTDOWN_TIMEOUT -force"
	$TOMCAT_HOME/bin/shutdown.sh $SHUTDOWN_OPTS
	RETVAL=$?
	echo -n "Stopping $NAME"
	if [ $RETVAL = 0 ]; then
		rm -f $TOMCAT_LOCK
		echo_success
	else
		echo_failure	
	fi	
	echo
}


case "$1" in
	start)
		start
		;; 
	stop)
		if [ -s "$CATALINA_PID" ]; then
			stop
		else
			echo "It seems like tomcat is not running. You may try force-stop"
			echo -n "Stopping $NAME"
			echo_warning
			echo
		fi 
		;; 
	force-stop)
		# this is useless on el7, and of dubious usefulness on el6
		stop
		;; 
	restart)
		$0 stop
		$0 start
		;; 
	status)
		status -p $CATALINA_PID $NAME
		;; 
	version)
		$TOMCAT_HOME/bin/catalina.sh version
		;;
	*) 
		echo "Usage: $0 {start|stop|force-stop|restart|status|version}"
		exit 1
esac
exit 0
