#!/bin/sh

### BEGIN INIT INFO
# Provides:          marcod
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: The marcopolo discoverer
# Description:       Marcopolo is a service discovering protocol
#                    based on multicast messaging.
### END INIT INFO

# Author: Diego Martin <martinarroyo@usal.es>
#

#FROM: https://twistedmatrix.com/trac/attachment/ticket/3434/twistdplugin

# Do NOT "set -e"

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
TWISTED_NAME="marcod"
DESC="The marcopolo discoverer"
DAEMON=$(which twistd)
SERVICE_NAME="/etc/marcopolo/daemon/marco_twistd.tac"
#SERVICE_DIR=/home/user/twistedplugin

PIDFILE=/var/run/${TWISTED_NAME}.pid
LOGFILE=/var/log/marcopolo/${TWISTED_NAME}-twistd.log

DAEMON_OPTS="--pidfile=$PIDFILE --logfile=$LOGFILE -y $SERVICE_NAME"

# Set python path so twistd can find the plugin
# See: http://twistedmatrix.com/projects/core/documentation/howto/plugin.html
#export PYTHONPATH=$SERVICE_DIR

if [ ! -x $DAEMON ]; then
  echo "ERROR: Can't execute $DAEMON."
  exit 1
fi

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions

start_service() {
  echo -n " * Starting $TWISTED_NAME... "
  start-stop-daemon -Sq -p $PIDFILE -x $DAEMON -- $DAEMON_OPTS
  e=$?
  if [ $e -eq 1 ]; then
    echo "already running"
    return
  fi

  if [ $e -eq 255 ]; then
    echo "couldn't start :("
    return
  fi

  echo "done"
}

stop_service() {
  echo -n " * Stopping $TWISTED_NAME... "
  start-stop-daemon -Kq -R 10 -p $PIDFILE
  e=$?
  if [ $e -eq 1 ]; then
    echo "not running"
    return
  fi

  echo "done"
}

case "$1" in
  start)
    start_service
    ;;
  stop)
    stop_service
    ;;
  restart)
    stop_service
    start_service
    ;;
  status)
    status_of_proc "$DAEMON" "$TWISTED_NAME" && exit 0 || exit $?
    ;;
  *)
    echo "Usage: /etc/init.d/$SERVICE_NAME {start|stop|restart|status}" >&2
    exit 1   
    ;;
esac

exit 0