#!/bin/bash
### BEGIN INIT INFO
#
# tigase        This starts and stops the Tigase XMPP server.
#
# chkconfig: 345 85 15
# description: Tigase is a XMPP server.
#
# processname: tigase
# pidfile: /var/run/tigase/tigase.pid
# config: /home/tigase/tigase-server/etc/tigase.conf
#
### management instructions
##
## to install: /sbin/chkconfig --add tigase
## to check:   /sbin/chkconfig --list tigase
## to start:   /sbin/chkconfig tigase <on|off|reset>
##
### END INIT INFO

# Settings paths and other variables

JAVA_HOME=/usr/lib/jvm/java/

USERNAME=tigase
USERGROUP=tigase
NAME=tigase
DESC="Tigase XMPP server"

TIGASE_HOME=/home/tigase/tigase-server
TIGASE_LIB=${TIGASE_HOME}/jars
TIGASE_CONFIG=/etc/tigase/tigase-server.xml
TIGASE_OPTIONS=
TIGASE_PARAMS=

PIDFILE=
TIGASE_CONSOLE_LOG=

USER=$USERNAME
eval HOME="~$USER"

# Attempt to locate JAVA_HOME, code borrowed from jabref package
if [ -z $JAVA_HOME ]
then
	for java_dir in /usr/lib/jvm/java-6-* ; do
		test -d ${java_dir} && JAVA_HOME=${java_dir}
	done
fi

# Include tigase defaults if available
if [ -z "${TIGASE_PARAMS}" ] ; then
	if [ -r "/etc/default/tigase" ] ; then
		TIGASE_PARAMS="/etc/default/tigase"
	elif [ -r "/etc/tigase/tigase.conf" ] ; then
		TIGASE_PARAMS="/etc/tigase/tigase.conf"
	elif [ -r "${TIGASE_HOME}/etc/tigase.conf" ] ; then
		TIGASE_PARAMS="${TIGASE_HOME}/etc/tigase.conf"
	fi
fi

[[ -f "${TIGASE_PARAMS}" ]] && . ${TIGASE_PARAMS}

if [ -z "${JAVA_HOME}" ] ; then
	echo "JAVA_HOME is not set."
	echo "Please set it to correct value before starting the sever."
	exit 1
fi

PATH=/sbin:/bin:/usr/sbin:/usr/bin:${JAVA_HOME}/bin

# Find tigase-server jar
for j in ${TIGASE_HOME}/jars/tigase-server*.jar ; do
	if [ -f ${j} ] ; then
		TIGASE_JAR=${j}
		break
	fi
done

if [ -z "${TIGASE_CONSOLE_LOG}" ] ; then
    if [ -w "/var/log/${NAME}/" ] ; then
        TIGASE_CONSOLE_LOG="/var/log/${NAME}/tigase-console.log"
    elif [ -w "${TIGASE_HOME}/logs/" ] ; then
        TIGASE_CONSOLE_LOG="${TIGASE_HOME}/logs/tigase-console.log"
    else
        TIGASE_CONSOLE_LOG="/dev/null"
    fi
fi

if [ -z "${PIDFILE}" ] ; then
    if [ -w "/var/run/" ] ; then
    	if [ ! -d "/var/run/$NAME/" ]; then
    		mkdir "/var/run/$NAME/";
    		chown $USERNAME:$USERGROUP "/var/run/$NAME/";
    	fi
        PIDFILE="/var/run/$NAME/$NAME.pid"
    elif [ -w "${TIGASE_HOME}/logs/" ] ; then
        PIDFILE="${TIGASE_HOME}/logs/$NAME.pid"
    else
        PIDFILE="/var/tmp/$NAME.pid"
    fi
fi

[[ -z "${TIGASE_RUN}" ]] && \
	TIGASE_RUN="tigase.server.XMPPServer -c ${TIGASE_CONFIG} ${TIGASE_OPTIONS}"

[[ -z "${JAVA}" ]] && JAVA="${JAVA_HOME}/bin/java"

[[ -z "${CLASSPATH}" ]] || CLASSPATH="${CLASSPATH}:"

CLASSPATH="${CLASSPATH}${TIGASE_JAR}"

for lib in ${TIGASE_LIB}/*.jar ; do
	CLASSPATH="${CLASSPATH}:$lib"
done

TIGASE_CMD="${JAVA_OPTIONS} -cp ${CLASSPATH} ${TIGASE_RUN}"

if [ -d "${TIGASE_HOME}" ] ; then
	cd ${TIGASE_HOME}
else
	echo "${TIGASE_HOME} is not set to correct value"
	echo "Please set it to correct value before starting the sever."
	exit 1
fi


# Source function library.
. /etc/rc.d/init.d/functions


#Helper functions
function checkRunning {
	local pid="$1"
	if [ -z "$pid" -o "$pid" == " " ]; then
		return 1;
	fi
	
	if [ ! -e /proc/$pid ]; then
		rm -f $PIDFILE; return 1;
	fi
return 0;
}

function getPid {
	if [ ! -f $PIDFILE ]; then
		return 1;
	fi
	PID="$(<$PIDFILE)"
	checkRunning $PID || return 1
return 0;
}

start() {
	getPid
	if [ $? -eq 0 ]; then
		echo -ne "Tigase is already running!"
	return 1
	fi
	
	rm -f $PIDFILE
	local cmd="cd ${TIGASE_HOME}; setsid $JAVA $TIGASE_CMD >>${TIGASE_CONSOLE_LOG} 2>&1 & echo \$! >$PIDFILE"
	su - ${USERNAME} -c "$cmd" || return 1
	
	sleep 1
	PID="$(<$PIDFILE)"
	if checkRunning $PID; then :; else
		echo -ne "Tigase start failed, see logfile."
		return 1
	fi
	
	echo -ne "Tigase started"
	return 0
}

stop() {
    getPid
	if [ $? -ne 0 ]; then
        echo -ne "Tigase is not running!"
        return 1
    fi

    kill $PID || return 1
    for ((i=0; i<15*10; i++)); do
        checkRunning $PID
            if [ $? -ne 0 ]; then
                rm -f $PIDFILE
                return 0
            fi
        sleep 1
        done

    echo -ne "Tigase did not terminate within 15 seconds, sending SIGKILL..."

    kill -s KILL $PID || return 1
    for ((i=0; i<15*10; i++)); do
        checkRunning $PID
        if [ $? -ne 0 ]; then
            rm -f $PIDFILE
            return 0
        fi
    sleep 0.1
    done
    echo -ne "Error: Tigase could not be stopped"
    return 1
}

case "$1" in
	start)
	echo "Starting $DESC"
	if start; then
		success
		echo
		exit 0
	else
		failure
		echo
		exit 1
	fi
	echo
	;;


	stop)
	echo "Stopping $DESC"
	if stop; then
		success
		echo
		exit 0
	else
		failure
		echo
		exit 1
	fi
	echo
	;;


	restart|force-reload)
	echo "Restarting $DESC"
	stop
	sleep 10
	if start; then
		success
		echo
		exit 0
	else
		failure
		echo
		exit 1
	fi
	echo
	;;

  clearrestart)
    $0 stop $2
    sleep 5
    $0 clear $2
    sleep 2
    $0 start $2
    ;;

  clear)
    LOGBACK="${TIGASE_HOME}/logs"`date "+%Y-%m-%d--%H:%M:%S"`
	echo "Clearing logs, moving backup to " ${LOGBACK}
	mkdir -p ${LOGBACK}
	mv "${TIGASE_HOME}/logs"/* ${LOGBACK}/
	if [ -n "${OSGI}" ] && ${OSGI} ; then
		echo "Clearing osgi cache"
		rm -rf "${TIGASE_HOME}/felix-cache"/*;
	fi
    ;;

	check)
	getPid
	echo "Checking arguments to Tigase: "
	echo
	echo "USERNAME            =  $USERNAME"
	echo "USERGROUP           =  $USERGROUP"
	echo "USER                =  $USER"
	echo "HOME                =  $HOME"
	echo "NAME                =  $NAME"
	echo
	echo "TIGASE_HOME         =  $TIGASE_HOME"
	echo "TIGASE_JAR          =  $TIGASE_JAR"
	echo "TIGASE_CMD          =  $TIGASE_CMD"
	echo "TIGASE_CONFIG       =  $TIGASE_CONFIG"
	echo "TIGASE_PARAMS       =  $TIGASE_PARAMS"
	echo "TIGASE_OPTIONS      =  $TIGASE_OPTIONS"
	echo "TIGASE_CONSOLE_LOG  =  $TIGASE_CONSOLE_LOG"
	echo "PIDFILE             =  $PIDFILE"
	echo "JAVA_HOME           =  $JAVA_HOME"
	echo "JAVA                =  $JAVA"
	echo "JAVA_OPTIONS        =  $JAVA_OPTIONS"
	echo "CLASSPATH           =  $CLASSPATH"

	if [ -f $PIDFILE ] && kill -0 `cat $PIDFILE` 2>/dev/null
	then
		echo "Tigase running pid="`cat $PIDFILE`
		exit 0
	fi
	exit 1
	;;

	*)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|clearrestart|clear|force-reload|check|status}" >&2
	exit 1
	;;
esac

exit 0
