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

%config
    syncthing_enable="$openpkg_rc_def"
    syncthing_flags="-gui-address=http://127.0.0.1:8384 -logflags=2"
    syncthing_log_prolog="true"
    syncthing_log_epilog="true"
    syncthing_log_numfiles="10"
    syncthing_log_minsize="1M"
    syncthing_log_complevel="9"

%common
    syncthing_statedir="@l_prefix@/var/syncthing/state"
    syncthing_pidfile="@l_prefix@/var/syncthing/run/syncthing.pid"
    syncthing_logfile="@l_prefix@/var/syncthing/log/syncthing.log"
    syncthing_signal () {
        [ -f $syncthing_pidfile ] && kill -$1 `cat $syncthing_pidfile`
    }

%status -u @l_rusr@ -o
    syncthing_usable="unknown"
    syncthing_active="no"
    rcService syncthing enable yes && \
        syncthing_signal 0 && syncthing_active="yes"
    echo "syncthing_enable=\"$syncthing_enable\""
    echo "syncthing_usable=\"$syncthing_usable\""
    echo "syncthing_active=\"$syncthing_active\""

%start -u @l_rusr@
    rcService syncthing enable yes || exit 0
    rcService syncthing active yes && exit 0
    (   GOMAXPROCS=32
        export GOMAXPROCS
        STNOUPGRADE=1
        export STNOUPGRADE
        nohup @l_prefix@/bin/syncthing \
            -home="$syncthing_statedir" \
            -logfile="$syncthing_logfile" \
            -no-browser \
            $syncthing_flags \
        </dev/null >>$syncthing_logfile 2>&1 &
        echo $! >$syncthing_pidfile
    ) >/dev/null 2>&1

%stop -u @l_rusr@
    rcService syncthing enable yes || exit 0
    rcService syncthing active no  && exit 0
    syncthing_signal TERM
    sleep 2
    rm -f $syncthing_pidfile >/dev/null 2>&1 || true

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

%daily -u @l_rusr@
    rcService syncthing enable yes || exit 0
    shtool rotate -f \
        -n ${syncthing_log_numfiles} -s ${syncthing_log_minsize} -d \
        -z ${syncthing_log_complevel} -m 664 -o @l_rusr@ -g @l_rgrp@ \
        -P "${syncthing_log_prolog}" \
        -E "${syncthing_log_epilog}; rc syncthing restart" \
        $syncthing_logfile

