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

%config
    chrony_enable="$openpkg_rc_def"
    chrony_mode="daemon"
    chrony_daemon_flags=""
    chrony_log_prolog="true"
    chrony_log_epilog="true"
    chrony_log_numfiles="10"
    chrony_log_minsize="1M"
    chrony_log_complevel="9"

%common
    chrony_pidfile="@l_prefix@/var/chrony/run/chrony.pid"
    chrony_signal () {
        [ -f $chrony_pidfile ] && kill -$1 `cat $chrony_pidfile`
    }
    chrony_once () {
        [ ".$1" != . ] && sleep $1
        @l_prefix@/sbin/chronyd -q
    }

%status -u @l_susr@ -o
    chrony_usable="unknown"
    chrony_active="no"
    rcService chrony enable yes && \
    [ ".$chrony_mode" = ".daemon" ] && \
        chrony_signal 0 && chrony_active="yes"
    echo "chrony_enable=\"$chrony_enable\""
    echo "chrony_usable=\"$chrony_usable\""
    echo "chrony_active=\"$chrony_active\""

%start -p 200 -u @l_susr@
    rcService chrony enable yes || exit 0
    rcService chrony active yes && exit 0

    #   under both periodical and daemon mode, synchronize local machine
    #   once manually -- either to fill the gap between startup time and
    #   the first run of the cron jobs (periodical mode) or to perform
    #   a possible large time offset which chronyd does not perform itself
    #   (daemon mode).
    case "$chrony_mode" in
        once | \
        daemon | \
        quarterly | hourly | daily | weekly | monthly )
            chrony_once
            ;;
    esac

    #   run the NTP daemon for continued synchronization
    if [ ".$chrony_mode" = .daemon ]; then
        @l_prefix@/sbin/chronyd \
            -u @l_nusr@ \
            ${chrony_daemon_flags}
    fi

%stop -p 800 -u @l_susr@
    rcService chrony enable yes || exit 0
    rcService chrony active no  && exit 0
    chrony_signal TERM
    rm -f $chrony_pidfile 2>/dev/null || true

%restart -p 200 -u @l_susr@
    rcService chrony enable yes || exit 0
    rcService chrony active no  && exit 0
    rc chrony stop start

%quarterly -p 800 -u @l_susr@
    rcService chrony enable yes || exit 0
    [ ".$chrony_mode" = .quarterly ] && chrony_once 30
    exit 0

%hourly -p 800 -u @l_susr@
    rcService chrony enable yes || exit 0
    [ ".$chrony_mode" = .hourly ] && chrony_once 30
    exit 0

%daily -p 800 -u @l_susr@
    rcService chrony enable yes || exit 0
    [ ".$chrony_mode" = .daily ] && chrony_once 30
    shtool rotate -f \
        -n ${chrony_log_numfiles} -s ${chrony_log_minsize} -d \
        -z ${chrony_log_complevel} -m 644 -o @l_susr@ -g @l_mgrp@ \
        -P "${chrony_log_prolog}" \
        -E "${chrony_log_epilog}; rc chrony restart" \
        @l_prefix@/var/chrony/log/chrony.log
    exit 0

%weekly -p 800 -u @l_susr@
    rcService chrony enable yes || exit 0
    [ ".$chrony_mode" = .weekly ] && chrony_once 30
    exit 0

%monthly -p 800 -u @l_susr@
    rcService chrony enable yes || exit 0
    [ ".$chrony_mode" = .monthly ] && chrony_once 30
    exit 0

