#!/bin/bash
#
# openfired	Stops and starts the Openfire XMPP service.
#
# chkconfig: 2345 99 1
# description: Openfire is an XMPP server, which is a server that facilitates \
#              XML based communication, such as chat.
# config: /opt/openfire/conf/openfire.xml
# pidfile: /var/run/openfired.pid
# 
# This script has currently been tested on Redhat and CentOS based systems,
# but should theoretically work on most UNIX like systems
#
# Before running this script make sure $OPENFIRE_HOME/bin/openfire.sh is
# executable by the user you want to run openfire as
# (chmod +x $OPENFIRE_HOME/bin/openfire.sh)
#
# This script should be copied into /etc/init.d and linked into
# your default runlevel directory.
# You can find your default runlevel directory by typing: 
# grep default /etc/inittab
#
# Link to the directory like follows
# cd /etc/rc<num>.d
# ln -s ../init.d/openfired S99openfired
#

# Get config.
[ -f /etc/sysconfig/openfire ] && . /etc/sysconfig/openfire

# If openfire user is not set in sysconfig, set to jive.
[ -z "$OPENFIRE_USER" ] && OPENFIRE_USER=jive

# If pid file path is not set in sysconfig, set to /var/run/openfired.pid.
[ -z "$OPENFIRE_PIDFILE" ] && OPENFIRE_PIDFILE=/var/run/openfired.pid

# -----------------------------------------------------------------

# If a openfire home variable has not been specified, try to determine it
if [ ! $OPENFIRE_HOME ]; then
	if [ -d "/opt/openfire" ]; then
		OPENFIRE_HOME="/opt/openfire"
	elif [ -d "/usr/local/openfire" ]; then
		OPENFIRE_HOME="/usr/local/openfire"
	else
		echo "Could not find Openfire installation under /opt or /usr/local"
		echo "Please specify the Openfire installation location in environment variable OPENFIRE_HOME"
		exit 1
	fi
fi

RETVAL=0
prog="openfired"

start() {
	OLD_PWD=`pwd`
	cd $OPENFIRE_HOME/bin

        # Start daemons.
        echo -n $"Starting $prog: "

	CMD=./openfire.sh
	su -s /bin/bash -c "$CMD" $OPENFIRE_USER &
	RETVAL=$?

	if [ $RETVAL -eq 0 -a ! -z "$OPENFIRE_PIDFILE" ]; then
		echo $! > $OPENFIRE_PIDFILE
	fi

	echo

	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/openfired

	sleep 1 # allows prompt to return
	cd $OLD_PWD
}

stop() {
	# Stop daemons.
	echo -n $"Shutting down $prog: "

	[ -f $OPENFILE_PIDFILE ] && kill `cat $OPENFIRE_PIDFILE`
	RETVAL=$?
	echo

	[ $RETVAL -eq 0 -a -f $OPENFIRE_PIDFILE ] && rm -f $OPENFIRE_PIDFILE
	[ $RETVAL -eq 0 -a -f /var/lock/subsys/openfired ] && rm -f /var/lock/subsys/openfired
}


case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		sleep 10 # since stop is backgrounded
		start
		;;
	status) 
		retval=$(pgrep -u $OPENFIRE_USER -f $OPENFIRE_HOME/bin/openfire.sh > /dev/null ; echo $?)
		if [ "$retval" = "0" ] ; then 
			echo "openfire is running"
			exit 0
		else 
			echo "openfire is not running"
			exit 0
		fi
		;;
	*)
		echo "Usage $0 {start|stop|restart|status}"
		exit 1
esac

exit 0
