#!/bin/bash
#
# This script will start tomcat if it not started or its PID
# doesn't indicate that it is running.
# It will check if $HOME/.tomcatstopped exist. If it does,
# it needs option '-f' to remove the file and start.
# (This allow admin to stop tomcat without stopping the cron.) 
#
# set -x

# 
# $HOME/.catalinarc defines many tomcat env variables
# We need CATALINA_HOME and CATALINA_PID.

addTornadoSupport(){
        TORNADO_HOME=/home/ctu/Tornado/IRMS3.0

        export LD_LIBRARY_PATH=$TORNADO_HOME/lib/jni/:$TORNADO_HOME/lib/dvl/extx:$LD_LIBRARY_PATH
export DMC_TABLE_PATH=$TORNADO_HOME/lib/dvl/extx/base2
}

startOpenOfficeService(){
export DISPLAY="localhost:1.0"
Xvfb :1 -screen 0 800x600x24 &
sleep 3
/opt/openoffice.org3/program/soffice  -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard -headless -nologo &
#/usr/lib/openoffice.org2.0/program/soffice -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard -headless -nologo &
}

# process options
for arg
do
case $arg in
   -f) /bin/rm -f $HOME/.tomcatstopped
	;;
   *) ;;  
esac
done

export LANG="zh_TW.UTF-8"
export LC_ALL="zh_TW.UTF-8"

if [ -f "$HOME/.tomcatstopped" ]
then

	echo "Warning: please run tomcatstart with -f option"
	exit 2
fi
 
if [ ! -f "$HOME/.catalinarc" ]
then
	echo "Error: missing $HOME/.catalinarc"
	exit 1
fi

. $HOME/.catalinarc

if [ ! -d "$CATALINA_HOME" ]
then
	echo "Error: missing definition of CATALINA_HOME"
	exit 1
fi

if [ -z "$CATALINA_PID" ]
then
	echo "Error: missing definition of CATALINA_PID"
	exit 1
fi
 

pid=`cat $CATALINA_PID 2>/dev/null`
if [ "$pid" != "" ] 
then 
	# check if pid exists and is java
	fname=`ps --no-headers --pid $pid -o fname` 
	if [ "$fname" != "java" ] 
	then 
		# pid file is out-of-date
		echo "CATALINA PID $pid is out-of-date, removing $CATALINA_PID"
		rm -f $CATALINA_PID
	else
		echo "tomcat already started !"
		exit 1
	fi
fi		


#nohup $JAVA_HOME/bin/rmiregistry &
#addTornadoSupport
#startOpenOfficeService

$CATALINA_HOME/bin/startup.sh
