#!/bin/sh

### BEGIN INIT INFO
# Provides:          schleuder-api-daemon
# Required-Start:    $local_fs $network $syslog
# Required-Stop:     $local_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Schleuder API daemon
# Description:       Schleuder API daemon — provides access for schleuder-cli and schleuder-web
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin

. /lib/init/vars.sh

. /lib/lsb/init-functions

NAME=schleuder-api-daemon
DAEMON=/usr/local/bin/schleuder-api-daemon
PIDFILE=/var/run/$NAME.pid
USER=schleuder
GROUP=schleuder

test -x $DAEMON || exit 5

start() {
  if [ -f /var/run/$NAME.pid ]; then
        log_failure_msg "$NAME is running already, please stop it first"
        exit 1
  fi

  if ! id $USER >/dev/null 2>&1; then
        log_failure_msg "User \"$USER\" does not exist"
        exit 1
  fi

  if ! getent group $GROUP >/dev/null 2>&1; then
        log_failure_msg "Group \"$GROUP\" does not exist"
        exit 1
  fi

  log_daemon_msg "Starting $NAME" "$DAEMON"
  start-stop-daemon --chuid "$USER":"$GROUP" --pidfile $PIDFILE --make-pidfile --background --exec $DAEMON --start
  log_end_msg $?
}

stop() {
  if ! [ -f /var/run/$NAME.pid ]; then
        log_failure_msg "$NAME isn't running currently, nothing to do"
        exit 1
  fi

  log_daemon_msg "Stopping $NAME" "$DAEMON"
  start-stop-daemon --oknodo --pidfile $PIDFILE --stop --retry 10
  log_end_msg $?
  rm $PIDFILE
}

restart() {
  stop
  start
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  *)
    log_success_msg "Usage: $0 {start|stop|restart}"
    exit 1
esac
