#! /bin/sh
### BEGIN INIT INFO
# Provides:          sci-web-tasks
# Required-Start:    $syslog $remote_fs
# Required-Stop:     $syslog $remote_fs
# Should-Start:      $network
# Should-Stop:       $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: sci-web background task worker
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/sci-web-tasks
NAME=sci-web-tasks
PIDFILE=/var/run/$NAME.pid
DESC="sci-web background task worker"

unset TMPDIR
test -x $DAEMON || exit 0
. /lib/lsb/init-functions

case "$1" in
  start)
        log_begin_msg "Starting $DESC: $NAME"
        # --exec /bin/sh --startas $DAEMON: sci-web-tasks is a #!/bin/sh
        # script, not an ELF binary, so plain --exec $DAEMON fails with
        # "not an ELF binary". Launching /bin/sh with the script as its
        # first argument works.
        #
        # start-stop-daemon -b does NOT write a pidfile in Debian 9
        # (stretch) sysvinit, so we write one explicitly after the
        # daemon is running. The pidfile tracks the sh wrapper; the
        # python child (manage.py process_tasks) is found via pkill in
        # the stop path.
        start-stop-daemon --start -b --quiet --pidfile "$PIDFILE" \
                --exec /bin/sh --startas "$DAEMON"
        rc=$?
        if [ $rc -eq 0 ]; then
                shpid=$(pgrep -f "^/bin/sh /usr/sbin/sci-web-tasks" 2>/dev/null | head -1)
                [ -n "$shpid" ] && echo "$shpid" > "$PIDFILE"
        fi
        log_end_msg $rc
        ;;
  stop)
        log_begin_msg "Stopping $DESC: $NAME"
        # Kill the sh wrapper by pidfile, then pkill any python
        # process_tasks children that outlived it (same pattern as the
        # websockify init script).
        start-stop-daemon --stop --quiet --pidfile "$PIDFILE" --exec /bin/sh
        pkill -f "manage.py process_tasks" 2>/dev/null || true
        rm -f "$PIDFILE"
        log_end_msg $?
        ;;
  restart)
        log_begin_msg "Restarting $DESC: $NAME"
        $0 stop
        $0 start
        log_end_msg $?
        ;;
  status)
        echo -n "Status of $DESC: "
        if [ ! -r "$PIDFILE" ]; then
                echo "$NAME is not running."
                exit 3
        fi
        if read pid < "$PIDFILE" && ps -p "$pid" > /dev/null 2>&1; then
                echo "$NAME is running."
                exit 0
        else
                echo "$NAME is not running but $PIDFILE exists."
                exit 1
        fi
        ;;
  *)
        N=/etc/init.d/${0##*/}
        echo "Usage: $N {start|stop|restart|status}" >&2
        exit 1
        ;;
esac

exit 0
