#!/bin/sh
#
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 Zimbra Software, LLC.
#
# The contents of this file are subject to the Zimbra Public License
# Version 1.4 ("License"); you may not use this file except in
# compliance with the License.  You may obtain a copy of the License at
# http://www.zimbra.com/license.
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
# ***** END LICENSE BLOCK *****
#
#
# Startup script for jetty under *nix systems
#
# Configuration files
#
# $HOME/.jettyrc
#   If it exists, this is read at the start of script. It may perform any
#   sequence of shell commands, like setting relevant environment variables.
#
# $JETTY_HOME/etc/jetty.xml
#   If found, used as this script's configuration file, but only if
#   /etc/jetty.conf was not present. See above.
#
# Configuration variables
#
# JAVA
#   Command to invoke Java. Java is found at runtime using Linux 'which' command.
#
# JAVA_OPTIONS
#   Extra options to pass to the JVM
#
# JETTY_HOME
#   Where Jetty is installed. If not set, the script will try go
#   guess it by first looking at the invocation path for the script,
#   and then by looking in standard locations as $HOME/opt/jetty
#   and /opt/jetty. The java system property "jetty.home" will be
#   set to this value for use by configure.xml files, f.e.:
#
#    <Arg><SystemProperty name="jetty.home" default="."/>/webapps/jetty.war</Arg>
#
# JETTY_CONSOLE
#   Where Jetty console output should go. Defaults to first writeable of
#      /dev/console
#      /dev/tty
#
# JETTY_PORT
#   Override the default port for Jetty servers. If not set then the
#   default value in the xml configuration file will be used. The java
#   system property "jetty.port" will be set to this value for use in
#   configure.xml files. For example, the following idiom is widely
#   used in the demo config files to respect this property in Listener
#   configuration elements:
#
#    <Set name="Port"><SystemProperty name="jetty.port" default="8080"/></Set>
#
#   Note: that the config file could ignore this property simply by saying:
#
#    <Set name="Port">8080</Set>
#
# JETTY_RUN
#   Where the jetty.pid file should be stored. It defaults to the
#   first available of /var/run, /usr/var/run, and /tmp if not set.
#
# JETTY_PID
#   The Jetty PID file, defaults to $JETTY_RUN/jetty.pid
#
# JETTY_ARGS
#   The default arguments to pass to jetty.
#

usage()
{
    echo "Usage: $0 {start|stop|run|restart|check|supervise} [ CONFIGS ... ] "
    exit 1
}

[ $# -gt 0 ] || usage

TMPJ=/tmp/j$$

##################################################
# Get the action & configs
##################################################

ACTION=$1

##################################################
# Set offline env. vars
##################################################

ZIMBRA_HOME="@install.data.root@"
ZIMBRA_PLATFORM="Linux"
JETTY_HOME="@install.app.root@/jetty"
CONFIGS="${ZIMBRA_HOME}/jetty/etc/jetty.xml"
#@install.leopard.java.home@

##################################################
# Find directory function
##################################################
findDirectory()
{
    OP=$1
    shift
    for L in $* ; do
        [ $OP $L ] || continue
        echo $L
        break
    done
}


##################################################
# See if there's a user-specific configuration file
##################################################
if [ -f $HOME/.jettyrc ] ; then
  . $HOME/.jettyrc
fi


##################################################
# Jetty's hallmark
##################################################
JETTY_INSTALL_TRACE_FILE="start.jar"


##################################################
# Try to determine JETTY_HOME if not set
##################################################
if [ -z "$ZIMBRA_HOME" ]
then
  ZIMBRA_HOME="/opt/zimbra/zdesktop dev"
fi

if [ -z "$JETTY_HOME" ]
then
  JETTY_HOME="$ZIMBRA_HOME/jetty"
fi


##################################################
# No JETTY_HOME yet? We're out of luck!
##################################################
if [ -z "$JETTY_HOME" ] ; then
    echo "** ERROR: JETTY_HOME not set, you need to set it or install in a standard location"
    exit 1
fi

#####################################################
# Check that jetty is where we think it is
#####################################################
if [ ! -r "$JETTY_HOME/$JETTY_INSTALL_TRACE_FILE" ]
then
   echo "** ERROR: Oops! Jetty doesn't appear to be installed in $JETTY_HOME"
   echo "** ERROR:  $JETTY_HOME/$JETTY_INSTALL_TRACE_FILE is not readable!"
   exit 1
fi

#########################################################################
# Zimbra tweak, because we want to keep jetty.conf under $JETTY_HOME/etc
#########################################################################
JAVA_OPTIONS="-DSTART='${JETTY_HOME}/etc/start.config' -Dzimbra.home='${ZIMBRA_HOME}' -Dzimbra.config='${ZIMBRA_HOME}/conf/localconfig.xml' -Djava.library.path='${JETTY_HOME}/../lib' -Djava.awt.headless=true -Djava.io.tmpdir='${ZIMBRA_HOME}/data/tmp/java' -Djava.net.useSystemProxies=true -Dsun.net.inetaddr.ttl=10 -XX:HeapDumpPath='${ZIMBRA_HOME}/heapdump/' -XX:+HeapDumpOnOutOfMemoryError"
JETTY_CONSOLE="${ZIMBRA_HOME}/log/zdesktop.out"
JETTY_RUN="${ZIMBRA_HOME}/log"
JETTY_PID="$JETTY_RUN/zdesktop.pid"
SHUTDOWN_FILE="$JETTY_RUN/offline.shutdown"

#####################################################
# Run the standard server if there's nothing else to run
#####################################################
if [ -z "$CONFIGS" ]
then
    CONFIGS="${JETTY_HOME}/etc/jetty.xml"
fi


#####################################################
# Find a location for the pid file
#####################################################
if [  -z "$JETTY_RUN" ]
then
  JETTY_RUN=`findDirectory -w /var/run /usr/var/run /tmp`
fi

#####################################################
# Find a PID for the pid file
#####################################################
if [  -z "$JETTY_PID" ]
then
  JETTY_PID="$JETTY_RUN/offline.pid"
fi

#####################################################
# Find a location for the jetty console
#####################################################
if [  -z "$JETTY_CONSOLE" ]
then
  if [ -w /dev/console ]
  then
    JETTY_CONSOLE=/dev/console
  else
    JETTY_CONSOLE=/dev/tty
  fi
fi


##################################################
# Find java on system
##################################################
if [ "$ZIMBRA_PLATFORM" == "MacOS" ]
then
    JAVA="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java"
    if [ -x "$JAVA" ]
    then
        JAVA_ERROR_FLAG=0
    else
        JAVA=`which java`
        JAVA_ERROR_FLAG=`"$JAVA" -version >/dev/null 2>&1; echo $?`
    fi
    if [ "$JAVA_ERROR_FLAG" == 0 ]
        then
            JAVA_VERSION_TEMP=`"$JAVA" -version 2>&1 | head -1`
            JAVA_VERSION=`expr "$JAVA_VERSION_TEMP" : '.*1\.\([0-9]\)'`
            if [ "$JAVA_VERSION" -lt "6" ]
            then
                echo "Current Java version is not supported. Please update Java to version 1.6 or later."
                exit 1
            else
                echo "JRE version $JAVA_VERSION is found on your system."
            fi
    else
        echo "JRE is not found on your system."
        exit 1
    fi
else
    JAVA=`which java`
    if [ "$JAVA" = "" ]
    then
        echo "JRE is not found on your system."
        exit 1
    else
        JAVA_VERSION=`expr "$($JAVA -version 2>&1 | head -1)" : '.*1\.\([0-9]\)'`
        if [ "$JAVA_VERSION" -lt "6" ]
        then
            echo "Current Java version is not supported. Please update Java to version 1.6 or later."
            exit 1
        else
            echo "JRE version $JAVA_VERSION is found on your system."
        fi
    fi
fi

#####################################################
# See if JETTY_PORT is defined
#####################################################
if [ "$JETTY_PORT" != "" ]
then
  JAVA_OPTIONS="$JAVA_OPTIONS -Djetty.port=$JETTY_PORT"
fi

#Dynamically set Xms/Xmx based on available memory

JAVA_HEAP="-Xms32m -Xmx512m"

JAVA_32BIT="-d32"
JAVA_STACKSIZE="-Xss150k"

if [ "$ZIMBRA_PLATFORM" = "MacOS" ]
then
    MEMSIZE=$(sysctl hw.memsize | awk '/^hw.memsize:/{print $2}')
    if [ $JAVA_VERSION -gt 6 ]
    then
        JAVA_32BIT=
        JAVA_STACKSIZE=
    fi
else
    MEMSIZE_TMP="$(free | awk '/^Mem:/{print $2}')"
    MEMSIZE=`expr $MEMSIZE_TMP \* 1000`
fi

if [ $MEMSIZE -gt 1000000000 ]
then
  JAVA_HEAP="-Xms128m -Xmx1024m"
fi

#####################################################
# Add jetty properties to Java VM options.
#####################################################
#MAILBOXD_JAVA_OPTIONS=`/opt/zimbra/bin/zmlocalconfig -m nokey mailboxd_java_options`
MAILBOXD_JAVA_OPTIONS="-client $JAVA_32BIT $JAVA_STACKSIZE -Djava.awt.headless=true $JAVA_HEAP -XX:MinHeapFreeRatio=20 -XX:MaxHeapFreeRatio=40 -XX:NewRatio=4 -XX:TargetSurvivorRatio=70 -XX:+UseConcMarkSweepGC"
JAVA_OPTIONS="$MAILBOXD_JAVA_OPTIONS $JAVA_OPTIONS -Djetty.home='$JETTY_HOME'"

#####################################################
# This is how the Jetty server will be started
#####################################################
RUN_CMD="'$JAVA' -da $JAVA_OPTIONS -jar '$JETTY_HOME/start.jar' $JETTY_ARGS '$CONFIGS'"

#####################################################
# Comment these out after you're happy with what
# the script is doing.
#####################################################
echo "JETTY_HOME     =  $JETTY_HOME"
echo "JETTY_RUN      =  $JETTY_RUN"
echo "JETTY_PID      =  $JETTY_PID"
echo "JETTY_CONSOLE  =  $JETTY_CONSOLE"
echo "JETTY_ARGS     =  $JETTY_ARGS"
echo "CONFIGS        =  $CONFIGS"
echo "JAVA_OPTIONS   =  $JAVA_OPTIONS"
echo "JAVA           =  $JAVA"


##################################################
# Do the action
##################################################
cd "${ZIMBRA_HOME}/log"

case "$ACTION" in
  start)
        echo "Starting Jetty: "

        if [ -f "$JETTY_PID" ]
        then
            PID=`cat "$JETTY_PID" 2>/dev/null`
            if [ -z $PID ]
            then
                echo "Empty pid file removed: $JETTY_PID"
                rm -f "$JETTY_PID"
            else
                if ps -f -p $PID | grep $JAVA > /dev/null 2>&1
                then
                    echo "Already Running!!"
                    alive=true
                    if [ -f "$SHUTDOWN_FILE" ]
                    then
                        echo "shutdown in progress; waiting"
                        timeout=15
                        while [ $timeout -gt 0 ]; do
                            if ps -f -p $PID | grep $JAVA > /dev/null 2>&1
                            then
                                sleep 1
                                timeout=$(($timeout - 1))
                            else
                                alive=false
                                break
                            fi
                        done
                    fi
                    if [ "$alive" = "true" ]
                    then
                        exit 1
                    fi
                else
                    echo "Stale pid file removed: $JETTY_PID"
                    rm -f "$JETTY_PID"
                fi
            fi
        fi

        echo "STARTED Jetty `date`" >> "$JETTY_CONSOLE"
        rm -f "$SHUTDOWN_FILE"

        nohup sh -c "exec $RUN_CMD >> '$JETTY_CONSOLE' 2>&1" >/dev/null &
        echo $! > "$JETTY_PID"
        echo "Jetty running pid="`cat "$JETTY_PID"`

        # mainly used by launchctl on mac
        if [ "$2" = "-w" ]
        then
            wait $!
        fi
        ;;

  stop)
        if [ ! -f "$JETTY_PID" ]
        then
            echo "No pid file found: $JETTY_PID"
            exit 1
        fi

        touch "$SHUTDOWN_FILE"

        PID=`cat "$JETTY_PID" 2>/dev/null`
        if [ -z $PID ]
        then
            echo "Empty pid file removed: $JETTY_PID"
            rm -f "$JETTY_PID"
            exit 1
        fi

        echo "Shutting down Jetty: $PID"
        kill $PID 2>/dev/null

        timeout=12
        while [ $timeout -gt 0 ]; do
            if ps -f -p $PID | grep $JAVA > /dev/null 2>&1
            then
                sleep 1
                timeout=$(($timeout - 1))
            else
                PID=''
                break
            fi
        done

        if [ ! -z $PID ]
        then
            kill -9 $PID 2>/dev/null
        fi

        rm -f "$JETTY_PID"
        echo "STOPPED `date`" >> "$JETTY_CONSOLE"
        ;;

  restart)
        $0 stop $*
        sleep 5
        $0 start $*
        ;;

  supervise)
       #
       # Under control of daemontools supervise monitor which
       # handles restarts and shutdowns via the svc program.
       #
         exec $RUN_CMD
         ;;

  run|demo)
        echo "Running Jetty: "

        if [ -f $JETTY_PID ]
        then
            echo "Already Running!!"
            exit 1
        fi

        exec $RUN_CMD
        ;;

  check)
        echo "Checking arguments to Jetty: "
        echo "JETTY_HOME     =  $JETTY_HOME"
        echo "JETTY_RUN      =  $JETTY_RUN"
        echo "JETTY_PID      =  $JETTY_PID"
        echo "JETTY_CONSOLE  =  $JETTY_CONSOLE"
        echo "JETTY_PORT     =  $JETTY_PORT"
        echo "CONFIGS        =  $CONFIGS"
        echo "JAVA_OPTIONS   =  $JAVA_OPTIONS"
        echo "JAVA           =  $JAVA"
        echo "CLASSPATH      =  $CLASSPATH"
        echo "RUN_CMD        =  $RUN_CMD"
        echo

        if [ -f "$JETTY_PID" ]
        then
            echo "Jetty running pid="`cat "$JETTY_PID"`
            exit 0
        fi
        exit 1
        ;;

*)
        usage
	;;
esac

exit 0


