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

%config
    dgraph_enable="$openpkg_rc_def"
    dgraph_daemons="@daemons@"
    dgraph_flags_zero=""
    dgraph_flags_server=""
    dgraph_log_prolog="true"
    dgraph_log_epilog="true"
    dgraph_log_numfiles="10"
    dgraph_log_minsize="1M"
    dgraph_log_complevel="9"

%common
    dgraph_cfgfile_zero="@l_prefix@/etc/dgraph/dgraph-zero.yaml"
    dgraph_pidfile_zero="@l_prefix@/var/dgraph/run/dgraph-zero.pid"
    dgraph_logfile_zero="@l_prefix@/var/dgraph/log/dgraph-zero.log"
    dgraph_cfgfile_server="@l_prefix@/etc/dgraph/dgraph-server.yaml"
    dgraph_pidfile_server="@l_prefix@/var/dgraph/run/dgraph-server.pid"
    dgraph_logfile_server="@l_prefix@/var/dgraph/log/dgraph-server.log"
    dgraph_signal () {
        [ -f $dgraph_pidfile_zero ] && \
            kill -$1 `cat $dgraph_pidfile_zero`
        local dgraph_pid_zero=$?
        [ -f $dgraph_pidfile_server ] && \
            kill -$1 `cat $dgraph_pidfile_server`
        local dgraph_pid_server=$?
        [    $dgraph_pid_zero -eq 0 \
          -o $dgraph_pid_server -eq 0 ]
    }

%status -u @l_rusr@ -o
    dgraph_usable="unknown"
    dgraph_active="no"
    rcService dgraph enable yes && \
        dgraph_signal 0 && dgraph_active="yes"
    echo "dgraph_enable=\"$dgraph_enable\""
    echo "dgraph_usable=\"$dgraph_usable\""
    echo "dgraph_active=\"$dgraph_active\""

%start -u @l_rusr@
    rcService dgraph enable yes || exit 0
    rcService dgraph active yes && exit 0
    (   GOMAXPROCS=32
        export GOMAXPROCS
        for daemon in $dgraph_daemons; do
            cmd="nohup @l_prefix@/sbin/dgraph $daemon"
            cmd="$cmd \$dgraph_flags_$daemon"
            cmd="$cmd --config \$dgraph_cfgfile_$daemon"
            cmd="$cmd </dev/null >>\$dgraph_logfile_$daemon 2>&1 &"
            eval "$cmd"
            eval "echo \$! >\$dgraph_pidfile_$daemon"
            sleep 1
        done
    ) >/dev/null 2>&1

%stop -u @l_rusr@
    rcService dgraph enable yes || exit 0
    rcService dgraph active no  && exit 0
    dgraph_signal TERM
    sleep 2
    pidfiles=""
    for daemon in $dgraph_daemons; do
        eval "pidfiles=\"\$pidfiles \$dgraph_pidfile_$daemon\""
    done
    rm -f $pidfiles >/dev/null 2>&1 || true

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

%daily -u @l_rusr@
    rcService dgraph enable yes || exit 0
    logfiles=""
    for daemon in $dgraph_daemons; do
        eval "logfiles=\"\$logfiles \$dgraph_logfile_$daemon\""
    done
    shtool rotate -f \
        -n ${dgraph_log_numfiles} -s ${dgraph_log_minsize} -d \
        -z ${dgraph_log_complevel} -m 664 -o @l_rusr@ -g @l_rgrp@ \
        -P "${dgraph_log_prolog}" \
        -E "${dgraph_log_epilog}; rc dgraph restart" \
        $logfiles

