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

%config
    consul_enable="$openpkg_rc_def"
    consul_flags=""
    consul_log_prolog="true"
    consul_log_epilog="true"
    consul_log_numfiles="10"
    consul_log_minsize="1M"
    consul_log_complevel="9"

%common
    consul_cfgdir="@l_prefix@/etc/consul"
    consul_datdir="@l_prefix@/var/consul/data"
    consul_pidfile="@l_prefix@/var/consul/run/consul.pid"
    consul_logfile="@l_prefix@/var/consul/log/consul.log"
    consul_signal () {
        [ -f $consul_pidfile ] && kill -$1 `cat $consul_pidfile`
    }

%status -u @l_rusr@ -o
    consul_usable="unknown"
    consul_active="no"
    rcService consul enable yes && \
        consul_signal 0 && consul_active="yes"
    echo "consul_enable=\"$consul_enable\""
    echo "consul_usable=\"$consul_usable\""
    echo "consul_active=\"$consul_active\""

%start -u @l_rusr@
    rcService consul enable yes || exit 0
    rcService consul active yes && exit 0
    (   GOMAXPROCS=32
        export GOMAXPROCS
        export CONSUL_UI_BETA=1
        nohup @l_prefix@/sbin/consul \
            agent \
            --config-dir "$consul_cfgdir" \
            --data-dir "$consul_datdir" \
            --pid-file "$consul_pidfile" \
            $consul_flags \
        </dev/null >>$consul_logfile 2>&1 &
    ) >/dev/null 2>&1

%stop -u @l_rusr@
    rcService consul enable yes || exit 0
    rcService consul active no  && exit 0
    consul_signal TERM
    i=0
    while [ $i -lt 10 ]; do
        sleep 1
        if ! consul_signal 0; then
            break
        fi
        i=`expr $i + 1`
    done
    rm -f $consul_pidfile >/dev/null 2>&1 || true

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

%reload -u @l_rusr@
    rcService consul enable yes || exit 0
    rcService consul active no  && exit 0
    @l_prefix@/sbin/consul reload

%daily -u @l_susr@
    rcService consul enable yes || exit 0
    shtool rotate -f \
        -n ${consul_log_numfiles} -s ${consul_log_minsize} -d \
        -z ${consul_log_complevel} -m 664 -o @l_rusr@ -g @l_rgrp@ \
        -P "${consul_log_prolog}" \
        -E "${consul_log_epilog}; rc consul reload" \
        $consul_logfile

