#!/bin/sh
# Tomcat init script
#
# chkconfig: 345 63 37
# description: Tomcat automatic startup and shutdown

export JAVA_HOME=/opt/jdk1.4
export CATALINA_HOME=/opt/tomcat

####################################################################################
# The checks below should all test for port 8009 if Apache is connected to Tomcat  #
# via mod_jk2 or similar. Otherwise test for port 8080 or whatever port is in use. #
####################################################################################

start(){
    su -m -s /bin/bash -c "$CATALINA_HOME/bin/catalina.sh start" tomcat
    #Test if tomcat is properly started
    netstat -ln | grep :8080 >& /dev/null
    res=$?
    count=0
    while [ $res -ne 0 -a $count -lt 30 ] ; do
        # wait a bit longer
        sleep 1;
        count=`expr $count + 1`
        echo -ne $count \\\r
        netstat -ln | grep :8080 >& /dev/null
        res=$?
    done

    if [ $count -lt 30 ]
      then
        RETVAL=0
        touch /var/lock/subsys/tomcat
      else
        RETVAL=1
    fi
}

stop(){
    su -mc "$CATALINA_HOME/bin/catalina.sh stop" tomcat
    sleep 5
    rm /var/lock/subsys/tomcat
    RETVAL=0
}

status(){
    #Test if tomcat is running
    netstat -ln | grep :8080 >& /dev/null
    RETVAL=$?
    if [ $RETVAL -eq 0 ]
      then
        echo "Tomcat is running"
      else
        echo "Tomcat is stopped"
    fi
}

restart(){
    stop
    start
}

# See how we were called.
case "$1" in
  start)
	  start
	  ;;
  stop)
	  stop
	  ;;
  status)
	  status
	  ;;
  restart|reload)
	  restart
	  ;;
  *)
	echo "Usage: tomcat {start|stop|status|restart|reload}"
	RETVAL=1
esac

exit $RETVAL
