#!/usr/bin/env bash

TOMCAT_USER="root"
TOMCAT_HOME="/usr/local/tomcat"
SHUTDOWN_WAIT=30 # Second

. /etc/profile
. /etc/bashrc

tomcat_pid() {
    echo $(ps -e -o pid= -o args= | grep "home=$TOMCAT_HOME " | awk '/org\.apache\.catalina\.startup\.Bootstrap/{print $1}')
}

start() {
    pid=$(tomcat_pid)
    if [ -n "$pid" ] ; then
        echo "Tomcat is already running (pid: $pid)"
    else
        # Start tomcat
        echo "Starting tomcat"
	if [ "$(whoami)" != "$TOMCAT_USER" ] ; then
          /bin/su -l $TOMCAT_USER -s /bin/bash -c "cd $TOMCAT_HOME/bin && $TOMCAT_HOME/bin/startup.sh"
        else
          cd $TOMCAT_HOME/bin && $TOMCAT_HOME/bin/startup.sh
        fi
    fi
    return 0
}

stop() {
    pid=$(tomcat_pid)
    if [ -n "$pid" ] ; then
        echo "Stoping Tomcat"
	if [ "$(whoami)" != "$TOMCAT_USER" ] ; then
          /bin/su -l $TOMCAT_USER -s /bin/bash -c "cd $TOMCAT_HOME/bin && $TOMCAT_HOME/bin/shutdown.sh"
        else
          cd $TOMCAT_HOME/bin && $TOMCAT_HOME/bin/shutdown.sh
        fi
        let kwait=$SHUTDOWN_WAIT
        count=0
        count_by=1

        until [ $(ps -p $pid | grep -c $pid) = '0' ] || [ $count -gt $kwait ] ; do
           echo "Waiting for processes to exit. Timeout before we kill the pid: ${count}/${kwait}"
           sleep $count_by
           let count=$count+$count_by;
        done
        if [ $count -gt $kwait ]; then
           echo "Killing processes which didn't stop after $SHUTDOWN_WAIT seconds"
           kill -9 $pid
        fi
    else
        echo "Tomcat is not running"
    fi

    return 0
}

if [ "$(whoami)" != "${TOMCAT_USER}" -a "$(whoami)" != "root" ] ; then
        echo "Run as ${TOMCAT_USER} user !!!"
        echo "su - ${TOMCAT_USER} -c $(pwd)/$0 $*"
        exit 1
fi

case $1 in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
       pid=$(tomcat_pid)
        if [ -n "$pid" ]
        then
           ## doly
           cntThread="$(cat /proc/$pid/status |grep Thread| awk '{print $2}')"
           echo "Tomcat is running with pid: $pid,  Thread Cnt : $cntThread"
        else
           echo "Tomcat is not running"
           exit 1
        fi
        ;;
    *)
        echo "Usage : $0 [start|stop|restart|status]"
        ;;
esac

exit 0
