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

%config
    cockroach_enable="$openpkg_rc_def"
    cockroach_flags=""
    cockroach_log_prolog="true"
    cockroach_log_epilog="true"
    cockroach_log_numfiles="10"
    cockroach_log_minsize="1M"
    cockroach_log_complevel="9"

%common
    cockroach_cfgfile="@l_prefix@/etc/cockroach/cockroach.conf"
    cockroach_logdir="@l_prefix@/var/cockroach/log"
    cockroach_pidfile="@l_prefix@/var/cockroach/run/cockroach.pid"
    cockroach_logfile="@l_prefix@/var/cockroach/log/cockroach.log"
    cockroach_signal () {
        [ -f $cockroach_pidfile ] && kill -$1 `cat $cockroach_pidfile`
    }

%status -u @l_rusr@ -o
    cockroach_usable="unknown"
    cockroach_active="no"
    rcService cockroach enable yes && \
        cockroach_signal 0 && cockroach_active="yes"
    echo "cockroach_enable=\"$cockroach_enable\""
    echo "cockroach_usable=\"$cockroach_usable\""
    echo "cockroach_active=\"$cockroach_active\""

%start -u @l_rusr@
    rcService cockroach enable yes || exit 0
    rcService cockroach active yes && exit 0
    (   GOMAXPROCS=32
        export GOMAXPROCS
        cmd="nohup @l_prefix@/bin/cockroach start"
        cmd="$cmd --log-dir=$cockroach_logdir"
        cmd="$cmd `cat $cockroach_cfgfile | \
            sed -e '/^[[:space:]]*#.*/d' \
                -e '/^[[:space:]]*$/d' \
                -e 's/^\([[:space:]]*\)\([a-zA-Z]\)/\1--\2/' | \
            sed -e ':a; $!N; s/\n/ /; ta' \
                -e 's;  *; ;g'`"
        cmd="$cmd $cockroach_flags"
        cmd="$cmd </dev/null >>$cockroach_logfile 2>&1 &"
        eval "$cmd"
        echo $! >$cockroach_pidfile
    ) >/dev/null 2>&1

%stop -u @l_rusr@
    rcService cockroach enable yes || exit 0
    rcService cockroach active no  && exit 0
    @l_prefix@/bin/cockroach quit
    sleep 4
    cockroach_signal TERM
    i=0
    while [ $i -lt 30 ]; do
        sleep 1
        if ! cockroach_signal 0; then
            break
        fi
        i=`expr $i + 1`
    done
    rm -f $cockroach_pidfile >/dev/null 2>&1 || true

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

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

%daily -u @l_susr@
    rcService cockroach enable yes || exit 0
    shtool rotate -f \
        -n ${cockroach_log_numfiles} -s ${cockroach_log_minsize} -d \
        -z ${cockroach_log_complevel} -m 664 -o @l_rusr@ -g @l_rgrp@ \
        -P "${cockroach_log_prolog}" \
        -E "${cockroach_log_epilog}; rc cockroach restart" \
        $cockroach_logfile

