#!/bin/bash
#
# spectrum:	XMPP transport to different networks
#
# Initscript author: Michal Schmidt <mschmidt@redhat.com>
#
# Copyright 2009 Red Hat, Inc.
# Released under GNU GPL v2 or (at your option) any later version.
#
# chkconfig: - 40 60
# description:	This is an XMPP transport/gateway to a wide range \
#		of different networks such as ICQ, XMPP (Jabber, GTalk), \
#		AIM, MSN, Facebook, Twitter, Gadu-Gadu, IRC and SIMPLE.
#
### BEGIN INIT INFO
# Provides: spectrum
# Required-Start: $local_fs $remote_fs $network $named
# Required-Stop:  $local_fs $remote_fs $network $named
# Default-Start:
# Default-Stop: 0 1 2 3 4 5 6
# Short-Description: Start/stop Spectrum XMPP transport
# Description: Start / stop the Spectrum XMPP transport
### END INIT INFO

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

exec=/usr/sbin/spectrum
spectrumctl=/usr/bin/spectrumctl
lockfile=/var/lock/subsys/spectrum

status() {
	# 0 if running
	# 1 if dead but pid file exists
	# 2 if dead but subsys locked
	# 3 if stopped
	STATUS=3
	[ -f $lockfile ] && STATUS=2
	OUTPUT=$($spectrumctl --machine-readable list)
	OLDIFS="$IFS"
	IFS=','
	while read pid name jid status; do
		case "$status" in
			"dead but pid-file exists")
				[ "$STATUS" -gt 1 ] && STATUS=1
				;;
			"running")
				STATUS=0
				;;
			"not running")
				;;
			*)
				echo "spectrumctl returned unknown status \"$status\""
		esac
	done <<< "$OUTPUT"
	IFS="$OLDIFS"
	case $STATUS in
		0) echo "spectrum is running" ;;
		1) echo "spectrum is dead but pid file exists" ;;
		2) echo "spectrum is dead but subsys locked" ;;
		3) echo "spectrum is stopped" ;;
	esac
	return $STATUS
}

start() {
	[ -x $exec ] || exit 5
	status > /dev/null && return 0
	echo $"Starting spectrum transport: "
	daemon $spectrumctl start
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch $lockfile && success || failure
	echo
	return $RETVAL
}

stop() {
	status > /dev/null || return 0
	echo $"Stopping spectrum transport: "
	$spectrumctl stop
	RETVAL=$?
	[ $RETVAL -eq 0 ] && rm -f $lockfile && success || failure
	echo
	return $RETVAL
}

restart() {
	stop
	start
}

reload() {
	restart
}

force_reload() {
	restart
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	status)
		status
		;;
	restart)
		restart
		;;
	reload)
		reload
		;;
	force-reload)
		force_reload
		;;
	condrestart|try-restart)
		status > /dev/null && restart
		;;
	*)
		echo $"Usage: $0 {start|stop|status|restart|try-restart|reload|force-reload}"
		exit 2
esac
exit $?
