#!/bin/bash
#
# geronimo11      This shell script takes care of starting and stopping Geronimo
#
# chkconfig: - 80 20
# description: Geronimo 1.1 is a J2EE-1.4 server
# processname: geronimo
# pidfile: /var/run/geronimo11.pid
# config: /etc/geronimo11.conf
#
# - originally written by Henri Gomez, Keith Irwin, and Nicolas Mailhot
# - heavily rewritten by Deepak Bhole and Jason Corley for tomcat5
#

# commented out until the RHEL and FC daemon functions converge
# Source the function library
#if [ -r "/etc/rc.d/init.d/functions" ]; then
    #. /etc/rc.d/init.d/functions
#fi

NAME="$(basename $0)"
unset ISBOOT
if [ "${NAME:0:1}" = "S" -o "${NAME:0:1}" = "K" ]; then
    NAME="${NAME:3}"
    ISBOOT="1"
fi

# For SELinux we need to use 'runuser' not 'su'
if [ -x "/sbin/runuser" ]; then
    SU="/sbin/runuser"
else
    SU="su"
fi

# Get the geronimo config (use this for environment specific settings)
GERONIMO_CFG="/etc/geronimo11.conf"
if [ -r "$GERONIMO_CFG" ]; then
    . ${GERONIMO_CFG}
fi

# Get instance specific config file
if [ -r "/etc/sysconfig/${NAME}" ]; then
    . /etc/sysconfig/${NAME}
fi

# Define which connector port to use
CONNECTOR_PORT="${CONNECTOR_PORT:-8080}"

GERONIMO_HOME="${GERONIMO_HOME:-/usr/share/geronimo11}"

GERONIMO_SERVER="${GERONIMO_SERVER:-minimal-jetty}"

# Path to the geronimo launch script
GERONIMO_START_SCRIPT="$GERONIMO_HOME/$GERONIMO_SERVER/bin/startup.sh"

# Path to the geronimo shutdown script
GERONIMO_STOP_SCRIPT="$GERONIMO_HOME/$GERONIMO_SERVER/bin/shutdown.sh"

# Geronimo program name
GERONIMO_PROG="$NAME"
        
# Define the geronimo username
GERONIMO_USER="${GERONIMO_USER:-geronimo}"

### Define the tomcat log file
##TOMCAT_LOG="${TOMCAT_LOG:-/var/log/tomcat5/catalina.out}"

RETVAL="0"

# remove when the RHEL and FC daemon functions converge
# (pulled from /etc/rc.d/init.d/functions)
function checkpid() {
    local i
    for i in $* ; do
        if [ -d "/proc/${i}" ]; then
            return 0
        fi
    done
    return 1
}

# remove when the RHEL and FC daemon functions converge
# (pulled from /etc/rc.d/init.d/functions)
function echo_failure() {
    echo -en "\\033[60G"
    echo -n "[  "
    echo -n $"FAILED"
    echo -n "  ]"
    echo -ne "\r"
    return 1
}

# remove when the RHEL and FC daemon functions converge
# (pulled from /etc/rc.d/init.d/functions)
function echo_success() {
    echo -en "\\033[60G"
    echo -n "[  "
    echo -n $"OK"
    echo -n "  ]"
    echo -ne "\r"
    return 0
}

# Look for open ports, as the function name might imply
function findFreePorts() {
    local isSet1="false"
    local isSet2="false"
    local isSet3="false"
    local lower="8000"
    randomPort1="0"
    randomPort2="0"
    randomPort3="0"
    local -a listeners="( $(
                        netstat -ntl | \
                        awk '/^tcp/ {gsub("(.)*:", "", $4); print $4}'
                    ) )"
    while [ "$isSet1" = "false" ] || \
          [ "$isSet2" = "false" ] || \
          [ "$isSet3" = "false" ]; do
        let port="${lower}+${RANDOM:0:4}"
        if [ -z `expr " ${listeners[*]} " : ".*\( $port \).*"` ]; then
            if [ "$isSet1" = "false" ]; then
                export randomPort1="$port"
                isSet1="true"
            elif [ "$isSet2" = "false" ]; then
                export randomPort2="$port"
                isSet2="true"
            elif [ "$isSet3" = "false" ]; then
                export randomPort3="$port"
                isSet3="true"
            fi
        fi
    done
}

function makeHomeDir() {
    if [ ! -d "$CATALINA_HOME" ]; then
        echo "$CATALINA_HOME does not exist, creating"
        if [ ! -d "/var/lib/${NAME}" ]; then
            mkdir -p /var/lib/${NAME}
            cp -pLR /var/lib/tomcat5/* /var/lib/${NAME}
        fi
        mkdir -p $CATALINA_HOME ${CATALINA_HOME}/conf /var/cache/${NAME}/temp \
                 /var/cache/${NAME}/work /var/log/${NAME}
        for i in temp work; do
            ln -fs /var/cache/${NAME}/${i} ${CATALINA_HOME}/${i}
        done
        for i in common server shared webapps; do
            ln -fs /var/lib/${NAME}/${i} ${CATALINA_HOME}/${i}
        done
        ln -fs /var/log/${NAME} ${CATALINA_HOME}/logs
        cp -pLR /etc/tomcat5/* ${CATALINA_HOME}/conf/
        cp -pLR /usr/share/tomcat5/bin $CATALINA_HOME
        cp -pLR /var/cache/tomcat5/work/* ${CATALINA_HOME}/work/
        chown ${TOMCAT_USER}:${TOMCAT_USER} /var/log/${NAME}
    fi
}

function parseOptions() {
    options=""
    options="$options $(
                 awk '!/^#/ && !/^$/ { ORS=" "; print "export ", $0, ";" }' \
                 $GERONIMO_CFG
             )"
    if [ -r "/etc/sysconfig/${NAME}" ]; then
        options="$options $(
                     awk '!/^#/ && !/^$/ { ORS=" "; 
                                           print "export ", $0, ";" }' \
                     /etc/sysconfig/${NAME}
                 )"
    fi
    GERONIMO_SCRIPT="$options $GERONIMO_SCRIPT"
}

# See how we were called.
function start() {
    echo -n "Starting ${GERONIMO_PROG}: "
    if [ -f "/var/lock/subsys/${NAME}" ] ; then
        if [ -f "/var/run/${NAME}.pid" ]; then
            read kpid < /var/run/${NAME}.pid
                if checkpid $kpid 2>&1; then
                    echo "$NAME process already running"
                        return -1
                    else
                        echo "lock file found but no process running for"
                        echo "pid $kpid, continuing"
                fi
        fi
    fi
    export GERONIMO_PID="/var/run/${NAME}.pid"
    touch $GERONIMO_PID
    chown ${GERONIMO_USER}:${GERONIMO_USER} $GERONIMO_PID
    if [ "$GERONIMO_HOME" != "/usr/share/geronimo11" ]; then
        # Create a geronimo directory if it doesn't exist
        makeHomeDir
        # If GERONIMO_HOME doesn't exist modify port number so that
        # multiple instances don't interfere with each other
        findFreePorts
        sed -i -e "s/8005/${randomPort1}/g" -e "s/8080/${CONNECTOR_PORT}/g" \
            -e "s/8009/${randomPort2}/g" -e "s/8443/${randomPort3}/g" \
            ${GERONIMO_HOME}/conf/server.xml
    fi
    $SU - $GERONIMO_USER -c "GERONIMO_PID=$GERONIMO_PID $GERONIMO_START_SCRIPT"
    RETVAL="$?"
    if [ "$RETVAL" -eq 0 ]; then 
        echo_success
        touch /var/lock/subsys/${NAME}
    else
        echo_failure
    fi
    echo
    return $RETVAL
}

function stop() {
    echo -n "Stopping $GERONIMO_PROG: "
    if [ -f "/var/lock/subsys/${NAME}" ]; then
        $SU - $GERONIMO_USER -c "$GERONIMO_STOP_SCRIPT"
        RETVAL="$?"
        if [ "$RETVAL" -eq "0" ]; then
            count="0"
            if [ -f "/var/run/${NAME}.pid" ]; then
                read kpid < /var/run/${NAME}.pid
                until [ "$(ps --pid $kpid | grep -c $kpid)" -eq "0" ] || \
                      [ "$count" -gt "$SHUTDOWN_WAIT" ]; do
                    echo -n -e "\nwaiting for processes $kpid to exit"
                    sleep 1
                    let count="${count}+1"
                done
                if [ "$count" -gt "$SHUTDOWN_WAIT" ]; then
                    echo -n -e "\nkilling processes which didn't stop after "
                    echo -n "$SHUTDOWN_WAIT seconds"
                    kill -9 $kpid
                fi
                echo_success
                if [ "$count" -gt "0" ]; then
                    echo -n -e "\n"
                fi
            fi
            rm -f /var/lock/subsys/$NAME /var/run/$NAME.pid
        else
            echo_failure
        fi
    fi
}


# See how we were called.
case "$1" in
    start)
        parseOptions
        start
        ;;
    stop)
        parseOptions
        stop
        ;;
    restart)
        parseOptions
        stop
        sleep 2    
        start
        ;;
    condrestart)
        if [ -f "/var/run/${NAME}.pid" ]; then
            parseOptions
            stop
            start
        fi
        ;;
    version)
        /usr/bin/unzip -qc \
            $(build-classpath geronimo11/system) \
            org/apache/geronimo/system/serverinfo/geronimo-version.properties \
		| grep version
        ;;
    *)
        echo "Usage: $GERONIMO_PROG {start|stop|restart|condrestart|version}"
        exit 1
esac

exit $RETVAL

