#!/bin/bash
#
#     This file is part of the Squashtest platform.
#     Copyright (C) 2010 - 2011 Squashtest TM, Squashtest.org
#
#     See the NOTICE file distributed with this work for additional
#     information regarding copyright ownership.
#
#     This is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Lesser General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
#
#     this software is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Lesser General Public License for more details.
#
#     You should have received a copy of the GNU Lesser General Public License
#     along with this software.  If not, see <http://www.gnu.org/licenses/>.
#
# /etc/init.d/squash-tm
# debian-compatible squash-tm startup script.
#
# Author: Karine Guilloux <kguilloux@henix.fr>
#
### BEGIN INIT INFO
# Provides:          squash-tm
# Required-Start:    $remote_fs $syslog $network
# Required-Stop:     $remote_fs $syslog $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start squash-tm at boot time
# Description:       Controls the Squash TM service
### END INIT INFO
#
# Do NOT "set -e"


# Main variables
PATH=/sbin:/usr/sbin:/bin:/usr/bin                   # PATH should only include /usr/* if it runs after the mountnfs.sh script
DESC="Squash TM Service"                             # Script description
NAME="squash-tm"                                     # Script name
SCRIPT_NAME="`pwd`/${NAME}"                          # Script service name
PID_DIR="/var/run/${NAME}"                           # PID directory
PID_FILE="${PID_DIR}/${NAME}.pid"                    # PID file
JAVA="`which java`"                                  # Java location 
DAEMON="${JAVA}"                                     # Daemon script

# Default variables also present in squash-tm default configuration file
SQUASH_HOME="/usr/share/${NAME}"                     # Squash home directory
SQUASH_USER="${NAME}"                                # User id to be invoked instead of root
SQUASH_GROUP="${NAME}"                               # Group id to be invoked instead of root
JAR_NAME="squash-tm.war"                             # Java main library
HTTP_PORT=8080                                       # Port for HTTP connector (default 8080; disable with -1)
# Default directory parameters
BUNDLES_DIR="/usr/share/${NAME}/bundles"             # Bundles directory (instead of: =../bundles )
CACHE_DIR="/var/cache/${NAME}"                       # Cache directory (instead of: =/. )
CONF_DIR="/etc/${NAME}"                              # Configurations directory (instead of: =../conf )
LOG_DIR="/var/log/${NAME}"                           # Log directory (instead of: =../logs )
TOMCAT_HOME="/var/lib/${NAME}"
TMP_DIR="/var/tmp"                                   # Tmp directory (instead of: =../tmp )
PLUGINS_DIR="/usr/share/${NAME}/plugins"             # Plugins directory (instead of =../plugins )
LUCENE_DIR="/var/cache/${NAME}/lucene-indexes"
# Default database parameters
DB_URL="jdbc:h2:///var/lib/${NAME}/data/${NAME}"     # DataBase URL (instead of: =jdbc:h2:../data/${NAME})
DB_USERNAME="sa"                                     # DataBase username
DB_PASSWORD="sa"                                     # DataBase password
DB_TYPE="h2"                                         # DataBase dialect


# Load environments
if [ -r /etc/default/locale ]
then
	. /etc/default/locale
	export LANG LANGUAGE
elif [ -r /etc/environment ]
then
	. /etc/environment
	export LANG LANGUAGE
fi

# Read configuration variable file if it is present
[ -r /etc/default/${NAME} ] && . /etc/default/${NAME}
#
DAEMON_ARGS="${JAVA_ARGS} -server -Djava.io.tmpdir=${TMP_DIR} -Dlogging.dir=${LOG_DIR} -jar ${JAR_NAME} --spring.profiles.active=${DB_TYPE} --spring.config.location=${CONF_DIR}/squash.tm.cfg.properties --squash.path.root=${SQUASH_HOME} --squash.path.bundles-path=${BUNDLES_DIR} --squash.path.plugins-path=${PLUGINS_DIR} --server.port=${HTTP_PORT} --server.tomcat.basedir=${TOMCAT_HOME} --hibernate.search.default.indexBase=${LUCENE_DIR} --logging.config=${CONF_DIR}/log4j2.xml"

export _JAVA_OPTIONS="-Dspring.datasource.url=${DB_URL} -Dspring.datasource.username=${DB_USERNAME} -Dspring.datasource.password=${DB_PASSWORD} -Duser.language=en"

if [ -z ${SQUASH_HOME} ]
then
	echo
	echo "Please ensure that SQUASH_HOME variable is correctly set."
	echo "You can define SQUASH_HOME in /etc/default/${NAME}"
	exit -3
fi

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions


#
# Function that checks the tcp port
#
check_tcp_port() 
{
	local service=$1
	local assigned=$2
	local default=$3

	if [ -n "${assigned}" ]
	then
		port=${assigned}
	else
		port=${default}
	fi

	count=`netstat --listen --numeric-ports | grep \:${port}[[:space:]] | grep -c . `
	if [ ${count} -ne 0 ]
	then
		echo "${NAME} : ERROR : The selected ${service} port (${port}) seems to be in use by another program!"
		echo "Please select another port to use for ${NAME}"
		return 1
	fi
}

#
# Function that starts the daemon/service
#
do_start()
{
	# The default location is /var/run/squash-tm/squash-tm.pid but the parent directory needs to be created if not exists
	if [ ! -d "${PID_DIR}" ]
	then
		mkdir ${PID_DIR} > /dev/null 2>&1 || true
		chown ${SQUASH_USER}:${SQUASH_GROUP} ${PID_DIR}
	fi

	# Verify that the squash-tm port is not already in use, jetty does not exit
	# even for BindException
	check_tcp_port "http" "${HTTP_PORT}" "8080" || return 1
	
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
	start-stop-daemon --start --quiet --pidfile ${PID_FILE} --background --make-pidfile -c ${SQUASH_USER} --test --exec ${DAEMON} > /dev/null \
		|| return 1
	start-stop-daemon --start --quiet --pidfile ${PID_FILE} --background --make-pidfile -c ${SQUASH_USER} --chdir ${BUNDLES_DIR} --exec ${DAEMON} -- \
		${DAEMON_ARGS} \
		|| return 2
	sleep 2
	chown ${SQUASH_USER}:${SQUASH_GROUP} ${PID_FILE}

	# Add code here, if necessary, that waits for the process to be ready
	# to handle requests from services started subsequently which depend
	# on this one.  As a last resort, sleep for some time.
}

#
# Function that stops the daemon/service
#
do_stop()
{
	# Return
	#   0 if daemon has been stopped
	#   1 if daemon was already stopped
	#   2 if daemon could not be stopped
	#   other if a failure occurred
	start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile ${PID_FILE} #--name ${NAME}
	RETVAL="$?"
	[ "$RETVAL" = 2 ] && return 2

	# Wait for children to finish too if this is a daemon that forks
	# and if the daemon is only ever run from this initscript.
	# If the above conditions are not satisfied then add some other code
	# that waits for the process to drop all resources that could be
	# needed by services started subsequently.  A last resort is to
	# sleep for some time.
	start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec ${DAEMON}
	[ "$?" = 2 ] && return 2

	# Many daemons don't delete their pidfiles when they exit.
	rm -f ${PID_FILE}
	return "$RETVAL"
}

# Make sure we run as root
if [ `id -u` -ne 0 ]
then
	echo "${NAME} : ERROR : The ${NAME} init script can only be run as root!";
	exit 1;
fi


#
# Main process
#
case "$1" in
	start)
		[ "${VERBOSE}" != no ] && log_daemon_msg "Starting ${DESC}" "${NAME}"
		do_start
		case "$?" in
			0|1) [ "${VERBOSE}" != no ] && log_end_msg 0
				 ;;
			2)   [ "${VERBOSE}" != no ] && log_end_msg 1
				 ;;
		esac
		;;

	stop)
		[ "${VERBOSE}" != no ] && log_daemon_msg "Stopping ${DESC}" "${NAME}"
		do_stop
		case "$?" in
			0|1) [ "${VERBOSE}" != no ] && log_end_msg 0
				 ;;
			2)   [ "${VERBOSE}" != no ] && log_end_msg 1
				 ;;
		esac
		;;

	status)
		status_of_proc "${DAEMON}" "${NAME}" && exit 0 || exit $?
		;;

	restart)
		[ "${VERBOSE}" != no ] && log_daemon_msg "Restarting ${DESC}" "${NAME}"
		do_stop
		case "$?" in
			0|1) do_start
				case "$?" in
					0) log_end_msg 0 ;;
					1) log_end_msg 1 ;; # Old process is still running
					*) log_end_msg 1 ;; # Failed to start
				esac
				;;
			*)   # Failed to stop
				log_end_msg 1
				;;
		esac
		;;

	*)
		echo "Usage: ${SCRIPT_NAME} {start|stop|status|restart}" >&2
		exit 3
		;;
esac

exit 0 
