#!/bin/sh -e
#
# /etc/init.d/jetty -- startup script for jetty 6.1.18
#
# Written by Philipp Meier <meier@meisterbohne.de>
# Modified for Jetty 6 by Ludovic Claude <ludovic.claude@laposte.net>
#
### BEGIN INIT INFO
# Provides:          jetty
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Should-Start:      $named
# Should-Stop:       $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start Jetty
# Description:       Start Jetty HTTP server and servlet container.
### END INIT INFO

# Configuration files
#
# /etc/default/jetty
#   If it exists, this is read at the start of script. It may perform any 
#   sequence of shell commands, like setting relevant environment variables.
#
# /etc/jetty/jetty.conf
#   If found, the file will be used as this script's configuration. 
#   Each line in the file may contain:
#     - A comment denoted by the pound (#) sign as first non-blank character.
#     - The path to a regular file, which will be passed to jetty as a 
#       config.xml file.
#     - The path to a directory. Each *.xml file in the directory will be
#       passed to jetty as a config.xml file.
#
#   The files will be checked for existence before being passed to jetty.
#
# /etc/jetty/jetty.xml
#   If found, used as this script's configuration file, but only if
#   /etc/jetty/jetty.conf was not present. See above.
#   
# Configuration variables (to define in /etc/default/jetty)
#
# JAVA_HOME  
#   Home of Java installation. 
#
# JAVA_OPTIONS
#   Extra options to pass to the JVM
#
# JETTY_PORT
#   Override the default port for Jetty servers. If not set then 8080
#   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>
#
# JETTY_ARGS
#   The default arguments to pass to jetty.
#
# JETTY_USER
#   if set, then used as a username to run the server as

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=jetty
DESC="Jetty servlet engine"
JETTY_HOME=/usr/share/$NAME
LOGDIR="/var/log/jetty"
START_JAR="$JETTY_HOME/start.jar"
START_DAEMON_JAR="$JETTY_HOME/start-daemon.jar"
DEFAULT=/etc/default/$NAME
DAEMON=/usr/bin/jsvc
JVM_TMP=/var/cache/jetty/tmp

if [ `id -u` -ne 0 ]; then
	echo "You need root privileges to run this script"
	exit 1
fi

# Make sure jetty is started with system locale
if [ -r /etc/default/locale ]; then
	. /etc/default/locale
	export LANG
fi

. /lib/lsb/init-functions

if [ -r /etc/default/rcS ]; then
	. /etc/default/rcS
fi


# The following variables can be overwritten in /etc/default/jetty

# Whether to start jetty (as a daemon) or not
NO_START=0

# Run Jetty as this user ID (default: jetty)
# Set this to an empty string to prevent Jetty from starting automatically
JETTY_USER=jetty
            
# Listen to connections from this network host (leave empty to accept all connections)
#JETTY_HOST=$(uname -n)
JETTY_HOST=

# The network port used by Jetty
JETTY_PORT=8080

# Additional arguments to pass to Jetty    
JETTY_ARGS=

# Extra options to pass to the JVM         
# Set java.awt.headless=true if JAVA_OPTIONS is not set so the
# Xalan XSL transformer can work without X11 display on JDK 1.4+
# It also sets the maximum heap size to 256M to deal with most cases.
JAVA_OPTIONS="-Xmx256m -Djava.awt.headless=true -Djava.library.path=/usr/lib"
                                           
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not
# defined in /etc/default/jetty). Should contain a list of space separated directories.
JDK_DIRS="
	  /usr/lib/jvm/default-java \
      /usr/lib/jvm/java-1.7.0-openjdk-* \
      /usr/lib/jvm/java-1.6.0-openjdk-* \
	  /usr/lib/jvm/java-6-sun \
	  /usr/lib/jvm/java-6-openjdk \
	  /usr/lib/jvm/java-1.5.0-sun \
	  /usr/lib/jvm/java-gcj \
	  /usr/lib/j2sdk1.6-sun \
	  /usr/lib/j2sdk1.5-sun \
	  /usr/lib/j2sdk1.5-ibm \
	  /usr/lib/j2sdk1.4-sun \
	  /usr/lib/j2sdk1.4 \
	  /usr/lib/j2se/1.4 \
	  /usr/lib/kaffe/ \
	 "

# Timeout in seconds for the shutdown of all webapps
JETTY_SHUTDOWN=30

# Jetty uses a directory to store temporary files like unpacked webapps
JETTY_TMP=/var/cache/jetty/data

# Jetty uses a config file to setup its boot classpath
JETTY_START_CONFIG=/etc/jetty/start.config

# End of variables that can be overwritten in /etc/default/jetty
                                                                                
# overwrite settings from default file
if [ -f "$DEFAULT" ]; then
	. "$DEFAULT"
fi

# Check whether jetty is still installed (it might not be if this package was
# removed and not purged)
if [ ! -r "$START_JAR" ]; then
	log_failure_msg "$NAME is not installed"
	exit 1
fi

[ -f "$DAEMON" ] || exit 0

# Check whether startup has been disabled
if [ "$NO_START" != "0" -a "$1" != "stop" ]; then 
	[ "$VERBOSE" != "no" ] && log_failure_msg "Not starting jetty - edit /etc/default/jetty and change NO_START to be 0 (or comment it out)."
	exit 0
fi

if [ -z "$JETTY_USER" ]; then
	log_failure_msg "Not starting/stopping $DESC as configured"
	log_failure_msg "(JETTY_USER is empty in /etc/default/jetty)."
	exit 0
fi

# Look for the right JVM to use
for jdir in $JDK_DIRS; do
	if [ -d "$jdir" -a -z "${JAVA_HOME}" ]; then
		JAVA_HOME="$jdir"
	fi
done
export JAVA_HOME

export JAVA="$JAVA_HOME/bin/java"

JAVA_OPTIONS="$JAVA_OPTIONS -Djava.io.tmpdir=$JETTY_TMP \
  -DSTART=$JETTY_START_CONFIG \
  -Djetty.home=$JETTY_HOME -Djetty.logs=$LOGDIR \
  -Djetty.host=$JETTY_HOST -Djetty.port=$JETTY_PORT"

# Set the JSP compiler if set in the jetty.default file
if [ -n "$JSP_COMPILER" ]; then
	JAVA_OPTS="$JAVA_OPTS -Dbuild.compiler=$JSP_COMPILER"
fi

export JAVA_OPTIONS
                                                                                
# Define other required variables
PIDFILE="/var/run/$NAME.pid"
WEBAPPDIR="$JETTY_HOME/webapps"
BOOTSTRAP_CLASS=org.mortbay.jetty.start.daemon.Bootstrap
JSVC_CLASSPATH="/usr/share/java/commons-daemon.jar:$START_JAR:$START_DAEMON_JAR:$JAVA_HOME/lib/tools.jar"
ROTATELOGS=/usr/sbin/rotatelogs
HOSTNAME=$(uname -n)

##################################################
# Check for JAVA_HOME
##################################################
if [ -z "$JAVA_HOME" ]; then
	log_failure_msg "Could not start $DESC because no Java Development Kit"
	log_failure_msg "(JDK) was found. Please download and install JDK 1.4 or higher and set"
	log_failure_msg "JAVA_HOME in /etc/default/jetty to the JDK's installation directory."
	exit 0
fi

CONFIG_LINES=$(cat /etc/jetty/jetty.conf | grep -v "^[[:space:]]*#" | tr "\n" " ")

##################################################
# Get the list of config.xml files from jetty.conf
##################################################
if [ ! -z "${CONFIG_LINES}" ] 
then
  for CONF in ${CONFIG_LINES} 
  do
    if [ ! -r "$CONF" ] 
    then
      log_warning_msg "WARNING: Cannot read '$CONF' specified in '$JETTY_CONF'" 
    elif [ -f "$CONF" ] 
    then
      # assume it's a configure.xml file
      CONFIGS="$CONFIGS $CONF" 
    elif [ -d "$CONF" ] 
    then
      # assume it's a directory with configure.xml files
      # for example: /etc/jetty.d/
      # sort the files before adding them to the list of CONFIGS
      XML_FILES=`ls ${CONF}/*.xml | sort | tr "\n" " "` 
      for FILE in ${XML_FILES} 
      do
         if [ -r "$FILE" ] && [ -f "$FILE" ] 
         then
            CONFIGS="$CONFIGS $FILE" 
         else
           log_warning_msg "WARNING: Cannot read '$FILE' specified in '$JETTY_CONF'" 
         fi
      done
    else
      log_warning_msg "WARNING: Don''t know what to do with '$CONF' specified in '$JETTY_CONF'" 
    fi
  done
fi

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

##################################################
# Do the action
##################################################
case "$1" in
  start)
	log_daemon_msg "Starting $DESC." "$NAME"
	if start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
	                --user "$JETTY_USER" --startas "$JAVA" > /dev/null; then 

		if [ -f $PIDFILE ] ; then
			log_warning_msg "$PIDFILE exists, but jetty was not running. Ignoring $PIDFILE"
		fi

		if [ -s "$LOGDIR/out.log" ]; then
			log_progress_msg "Rotate logs"
			$ROTATELOGS "$LOGDIR/out.log" 86400 \
				< "$LOGDIR/out.log" || true
		fi
		> "$LOGDIR/out.log"
		chown -R $JETTY_USER:adm "$LOGDIR"

		# Remove / recreate JETTY_TMP directory
		rm -rf "$JETTY_TMP"
		mkdir "$JETTY_TMP" || {
			log_failure_msg "could not create $DESC temporary directory at $JETTY_TMP"
			exit 1
		}
		chown $JETTY_USER "$JETTY_TMP"

		# Remove / recreate JVM_TMP directory
		rm -rf "$JVM_TMP"
		mkdir "$JVM_TMP" || {
			log_failure_msg "could not create JVM temporary directory at $JVM_TMP"
			exit 1
		}
		chown $JETTY_USER "$JVM_TMP"
		cd "$JVM_TMP"

		$DAEMON -user "$JETTY_USER" -cp "$JSVC_CLASSPATH" \
		    -outfile $LOGDIR/out.log -errfile $LOGDIR/out.log \
		    -pidfile "$PIDFILE" $JAVA_OPTIONS $BOOTSTRAP_CLASS \
		    $JETTY_ARGS $CONFIGS

		log_daemon_msg "$DESC started, reachable on http://$HOSTNAME:$JETTY_PORT/." "$NAME"

		sleep 5
		if start-stop-daemon --test --start --pidfile "$PIDFILE" \
			--user $JETTY_USER --startas "$JAVA" >/dev/null; then
			log_end_msg 1
		else
			log_end_msg 0
		fi

	else
		log_warning_msg "(already running)."
		log_end_msg 0
	fi
	;;

  stop)
	log_daemon_msg "Stopping $DESC (was reachable on http://$HOSTNAME:$JETTY_PORT/)." "$NAME"

	if start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
		--user "$JETTY_USER" --startas "$JAVA" > /dev/null; then
		if [ -x "$PIDFILE" ]; then
			log_warning_msg "(not running but $PIDFILE exists)."
		else
			log_warning_msg "(not running)."
		fi
	else
		start-stop-daemon --quiet --stop \
			--pidfile "$PIDFILE" --user "$JETTY_USER" \
			--startas "$JAVA" > /dev/null
		while ! start-stop-daemon --quiet --test --start \
			  --pidfile "$PIDFILE" --user "$JETTY_USER" \
			  --startas "$JAVA" > /dev/null; do 
			sleep 1
			log_progress_msg "."
			JETTY_SHUTDOWN=`expr $JETTY_SHUTDOWN - 1` || true
			if [ $JETTY_SHUTDOWN -ge 0 ]; then
				start-stop-daemon --oknodo --quiet --stop \
					--pidfile "$PIDFILE" --user "$JETTY_USER" \
					--startas "$JAVA"
			else
				log_progress_msg " (killing) "
				start-stop-daemon --stop --signal 9 --oknodo \
					--quiet --pidfile "$PIDFILE" \
					--user "$JETTY_USER"
			fi
		done
		rm -f "$PIDFILE"
		rm -rf "$JVM_TMP"
		rm -rf "$JETTY_TMP/*"
		log_daemon_msg "$DESC stopped." "$NAME"
		log_end_msg 0
	fi
	;;

  status)
	if start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
		--user "$JETTY_USER" --startas "$JAVA" > /dev/null; then

		if [ -f "$PIDFILE" ]; then
		    log_success_msg "$DESC is not running, but pid file exists."
			exit 1
		else
		    log_success_msg "$DESC is not running."
			exit 3
		fi
	else
		log_success_msg "$DESC is running with pid `cat $PIDFILE`, and is reachable on http://$JETTY_HOST:$JETTY_PORT/"
	fi
	;;

  restart|force-reload)
	if ! start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
		--user "$JETTY_USER" --startas "$JAVA" > /dev/null; then
		$0 stop $*
		sleep 1
	fi
	$0 start $*
	;;

  try-restart)
	if start-stop-daemon --quiet --test --start --pidfile "$PIDFILE" \
		--user "$JETTY_USER" --startas "$JAVA" > /dev/null; then
		$0 start $*
	fi
	;;

  check)
	log_success_msg "Checking arguments for Jetty: "
	log_success_msg ""
	log_success_msg "PIDFILE        =  $PIDFILE"
	log_success_msg "JAVA_OPTIONS   =  $JAVA_OPTIONS"
	log_success_msg "JAVA           =  $JAVA"
	log_success_msg "JETTY_USER     =  $JETTY_USER"
	log_success_msg "JETTY_HOST     =  $JETTY_HOST"
	log_success_msg "JETTY_PORT     =  $JETTY_PORT"
	log_success_msg "ARGUMENTS      =  $ARGUMENTS"
        
	if [ -f $PIDFILE ]
	then
		log_success_msg "$DESC is running with pid `cat $PIDFILE`, and is reachable on http://$JETTY_HOST:$JETTY_PORT/"
		exit 0
	fi
	exit 1
	;;

  *)
	log_success_msg "Usage: $0 {start|stop|restart|force-reload|try-restart|status|check}"
	exit 1
	;;
esac

exit 0
