#!/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

NAME="marcod"
DESC="The marcopolo discoverer"
DAEMON=/usr/local/bin/marcod

PIDFILE=/var/run/${NAME}.pid
DAEMON_OPTS=


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 $NAME... "
  start-stop-daemon -Sq -p $PIDFILE -x $DAEMON --make-pidfile -- $DAEMON_OPTS &> /dev/null
  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 $NAME... "
  start-stop-daemon -Kq -R 10 -p $PIDFILE &>/dev/null
  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" "$NAME" && exit 0 || exit $?
    ;;
  *)
    echo "Usage: /etc/init.d/$SERVICE_NAME {start|stop|restart|status}" >&2
    exit 1   
    ;;
esac

exit 0