#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          zm-rpcapi
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Should-Start:      mysql postgresql
# Should-Stop:       mysql postgresql
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: A JSON-RPC frontend for Zonemaster Backend
# Description:       zm-rpcapi lets you add new tests and check for results in
#                    the the Zonemaster Backend database
### END INIT INFO

BINDIR=${ZM_BACKEND_BINDIR:-/usr/local/bin}
LOGFILE=${ZM_BACKEND_LOGFILE:-/var/log/zonemaster/zm-rpcapi.log}
PIDFILE=${ZM_BACKEND_PIDFILE:-/var/run/zonemaster/zm-rpcapi.pid}
LISTENIP=${ZM_BACKEND_LISTENIP:-127.0.0.1}
LISTENPORT=${ZM_BACKEND_LISTENPORT:-5000}
USER=${ZM_BACKEND_USER:-zonemaster}
GROUP=${ZM_BACKEND_GROUP:-zonemaster}

STARMAN=`PATH="$PATH:/usr/local/bin" /usr/bin/which starman`
#export ZM_BACKEND_RPCAPI_LOGLEVEL='warning'  # Set this variable to override the default log level

. /lib/lsb/init-functions

start () {
    $STARMAN --listen=$LISTENIP:$LISTENPORT --preload-app --user=$USER --group=$GROUP --pid=$PIDFILE --error-log=$LOGFILE --daemonize $BINDIR/zonemaster_backend_rpcapi.psgi || exit 1
}

stop () {
    if [ -f $PIDFILE ]
    then
        kill `cat $PIDFILE`
    fi
}

status () {
    status="0"
    pidofproc -p "$PIDFILE" starman >/dev/null || status="$?"
    if [ "$status" = 0 ]; then
        log_success_msg "zm-rpcapi is running"
        return 0
    elif [ "$status" = 4 ]; then
        log_failure_msg "could not access PID file for zm-rpcapi"
        return $status
    else
        log_failure_msg "zm-rpcapi is not running"
        return $status
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart|force-reload)
        stop
        start
        ;;
    status)
        status
        ;;
    *)
        echo "usage: $0 [start|stop|restart|force-reload|status]"
        exit 1
esac
exit 0
