#!/bin/sh
#
# spectrum (this script) - manage multiple spectrum (XMPP Transport) instances
# Copyright (C) 2009 Thilo Cestonaro <thilo@cestona.ro>
# Distributable under the terms of the GNU GPL version 2.
#

### BEGIN INIT INFO
# Provides:             spectrum
# Required-Start:       $network $local_fs $remote_fs
# Required-Stop:
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Spectrum XMPP Transport Service
### END INIT INFO


set -e

USER=spectrum
CONFSDIR=/etc/spectrum/
DAEMON=/usr/local/bin/spectrum
LOGPATH=/var/log/spectrum
PIDPATH=/var/run/spectrum


test -x "$DAEMON" || exit 0

if [ ! -d "$PIDPATH" ]; then
	mkdir "$PIDPATH";
	chown $USER.adm "$PIDPATH";
fi

# Check that user exists
check_user() {
	if ! getent passwd $USER >/dev/null; then
		exit 1;
	fi
}

. /lib/lsb/init-functions

case "$1" in
  start)
    check_user
    for i in $CONFSDIR/* ; do
      if grep "enable" $i | grep "=" | grep "1" > /dev/null ; then
        CONF=`basename $i`
        log_daemon_msg "Starting spectrum instance:" "$CONF"
        if start-stop-daemon --start --quiet --oknodo --pidfile "$PIDPATH/$CONF.pid" --chuid "$USER" --exec "$DAEMON" --make-pidfile --background -- "$CONFSDIR/$CONF" -l "$LOGPATH/$CONF.log" -n ; then
          log_end_msg 0
        else
          log_end_msg 1
        fi
      fi
    done
    ;;
  stop)
    for i in $CONFSDIR/* ; do
      if grep "enable" $i | grep "=" | grep "1" > /dev/null ; then
        CONF=`basename $i`
        log_daemon_msg "Stopping spectrum instance:" "$CONF"
        if start-stop-daemon --stop --retry 30 --quiet --oknodo --pidfile "$PIDPATH/$CONF.pid"; then
          if [ -e "$PIDPATH/$CONF.pid" ] ; then
            rm "$PIDPATH/$CONF.pid"
          fi
          log_end_msg 0
        else
          log_end_msg 1
        fi
      fi
    done
    ;;
  *)
    log_action_msg "Usage: /etc/init.d/spectrum {start|stop}"
    exit 1
esac
      
exit 0;
