#!@l_prefix@/bin/openpkg rc
##
##  rc.nsq -- Run-Commands
##

%config
    nsq_enable="$openpkg_rc_def"
    nsq_log_prolog="true"
    nsq_log_epilog="true"
    nsq_log_numfiles="10"
    nsq_log_minsize="1M"
    nsq_log_complevel="9"

%common
    nsq_cfgfile="@l_prefix@/etc/nsq/nsqd.cfg"
    nsq_pidfile="@l_prefix@/var/nsq/run/nsq.pid"
    nsq_logfile="@l_prefix@/var/nsq/log/nsq.log"
    nsq_start () {
        for daemon in nsqd nsqlookupd nsqadmin; do
            (   nohup @l_prefix@/sbin/$daemon -config @l_prefix@/etc/nsq/$daemon.cfg \
                </dev/null >>@l_prefix@/var/nsq/log/$daemon.log 2>&1 &
                echo $! >@l_prefix@/var/nsq/run/$daemon.pid
            ) >/dev/null 2>&1
        done
    }
    nsq_signal () {
        [ -f @l_prefix@/var/nsq/run/$1.pid ] && \
        kill -$2 `cat @l_prefix@/var/nsq/run/$1.pid`
    }
    nsq_status () {
        (   status=0
            for daemon in nsqd nsqlookupd nsqadmin; do
                if nsq_signal $daemon 0; then
                    :
                else
                    status=1
                    break
                fi
            done
            exit $status
        )
    }
    nsq_stop () {
        for daemon in nsqd nsqlookupd nsqadmin; do
            nsq_signal $daemon TERM
        done
        sleep 1
        for daemon in nsqd nsqlookupd nsqadmin; do
            rm -f @l_prefix@/var/nsq/run/$daemon.pid
        done
    }

%status -u @l_rusr@ -o
    nsq_usable="unknown"
    nsq_active="no"
    rcService nsq enable yes && \
        nsq_status && nsq_active="yes"
    echo "nsq_enable=\"$nsq_enable\""
    echo "nsq_usable=\"$nsq_usable\""
    echo "nsq_active=\"$nsq_active\""

%start -u @l_rusr@
    rcService nsq enable yes || exit 0
    rcService nsq active yes && exit 0
    nsq_start

%stop -u @l_rusr@
    rcService nsq enable yes || exit 0
    rcService nsq active no  && exit 0
    nsq_stop

%restart -u @l_rusr@
    rcService nsq enable yes || exit 0
    rcService nsq active no  && exit 0
    rc nsq stop start

%daily -u @l_rusr@
    rcService nsq enable yes || exit 0
    shtool rotate -f \
        -n ${nsq_log_numfiles} -s ${nsq_log_minsize} -d \
        -z ${nsq_log_complevel} -m 664 -o @l_rusr@ -g @l_rgrp@ \
        -P "${nsq_log_prolog}" \
        -E "${nsq_log_epilog}; rc nsq restart" \
        $nsq_logfile

