#!/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
# 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/bin/spectrum #XXX should belong to sbin?
service=spectrum
configdir=/etc/spectrum
configsuffix=cfg
pidfiledir=/var/run/spectrum

status_one() {
	name=$1
	pidfile=$pidfiledir/$name.pid
	status -p $pidfile "$service-$name"
}

status_one_quiet() {
	status_one $1 > /dev/null 2>&1
}

start_one() {
	name=$1
	status_one_quiet $name && return 0
	conf=$configdir/$name.$configsuffix
	echo -n $"Starting spectrum transport ($name): "
	pidfile=$pidfiledir/$name.pid
	daemon --check $service --pidfile $pidfile \
		$exec -p $pidfile $conf
	RETVAL=$?
	echo
	return $RETVAL
}

stop_one() {
	name=$1
	status_one_quiet $name || return 0
	pidfile=$pidfiledir/$name.pid
	echo -n $"Stopping spectrum transport ($name): "
	killproc -p $pidfile $service
	RETVAL=$?
	echo
	return $RETVAL
}

restart_one() {
	name=$1
	stop_one $name
	start_one $name
}

for_all_configured() {
	do_action=$1
	configured=
	configs=`ls $configdir/*.$configsuffix 2>/dev/null`
	for conf in $configs; do
		configured=1
		name=`basename $conf .$configsuffix`
		$do_action $name
		RETVAL=$?
		[ $RETVAL -eq 0 ] || break
	done
	if [ -z "$configured" ]; then
		echo -n $"No spectrum transports configured "
		failure
		echo
		RETVAL=6
	fi
	return $RETVAL
}

for_all_running() {
	do_action=$1
	RETVAL=0
	pidfiles=`ls $pidfiledir/*.pid 2>/dev/null`
	for pidfile in $pidfiles; do
		name=`basename $pidfile .pid`
		$do_action $name
		RETVAL=$?
	done
	return $RETVAL
}

start_all_configured() {
	[ -x $exec ] || exit 5
	for_all_configured start_one
}

stop_all_running() {
	for_all_running stop_one
}

status_all_configured() {
	for_all_configured status_one
}

restart() {
	stop_all_running
	start_all_configured
}

reload() {
	restart
}

force_reload() {
	restart
}

# See how we were called.
case "$1" in
	start)
		start_all_configured
		;;
	stop)
		stop_all_running
		;;
	status)
		status_all_configured
		;;
	restart)
		restart
		;;
	reload)
		reload
		;;
	force-reload)
		force_reload
		;;
	condrestart|try-restart)
		for_all_running restart_one
		;;
	*)
		echo $"Usage: $0 {start|stop|status|restart|try-restart|reload|force-reload}"
		exit 2
esac
exit $?
