#!/bin/sh
### BEGIN INIT INFO
# Provides:          docker-swarm
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Should-Start:      $syslog
# Should-Stop:       $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: docker swarm manager
# Description: Start docker swarm manager
### END INIT INFO

NAME=$(basename $(readlink -f $0))
DAEMON=/usr/bin/$NAME
LOGFILE=/var/log/$NAME.log
PIDFILE=/var/run/$NAME.pid
DAEMON_USER=nobody
DAEMON_ARGS=""

# Exit if executable is not installed
[ -x "$DAEMON" ] || exit 0

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

RETRY=TERM/30/KILL/5

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
. /lib/lsb/init-functions

_ev_ () {
  local rv_=$?
  [ "$VERBOSE" = "no" ] || eval $@
  return $rv_
}

case "$1" in
    start)
        _ev_ log_action_begin_msg \"Starting $NAME\"
        if R=$($0 status); then
            _ev_ log_action_end_msg 0 \"$R\"
        else
            R=$(start-stop-daemon --start --pidfile $PIDFILE --make-pidfile --background \
                --chuid $DAEMON_USER --startas /usr/bin/pipexec -- -k \
                -- [ D $DAEMON $DAEMON_ARGS ] [ L /usr/bin/logger --tag $NAME ] '{D:2>D:1}' '{D:1>L:0}')
            sleep 0.1
            $0 status >>/dev/null
            _ev_ log_action_end_msg $? \"$R\"
        fi
    ;;
    debug)
        OPTS="--logtostderr=true $OPTS"
        start-stop-daemon --start --exec $DAEMON --chuid $DAEMON_USER --pidfile $PIDFILE --make-pidfile -- $DAEMON_ARGS
    ;;
    stop)
        _ev_ log_action_begin_msg \"Stopping $NAME\"
        R=$(start-stop-daemon --stop --oknodo --user $DAEMON_USER --pidfile $PIDFILE --remove-pidfile --retry=$RETRY 2>&1)
        _ev_ log_action_end_msg $? \"$R\"
    ;;
    status)
        ## return status 0 if process is running.
        status_of_proc -p $PIDFILE "$DAEMON" "$NAME"
    ;;
    restart|force-reload)
        $0 stop
        $0 start
    ;;
    *)
        echo "Usage: /etc/init.d/$NAME {start|debug|stop|restart|force-reload|status}" >&2
        exit 1
    ;;
esac
