#!@l_prefix@/lib/openpkg/bash @l_prefix@/etc/rc
##
##  rc.ntp -- Run-Commands for NTP Daemon
##

%config
    ntp_enable="yes"
    ntp_daemon="yes"
    ntp_log_prolog="true"
    ntp_log_epilog="true"
    ntp_log_numfiles="10"
    ntp_log_minsize="1M"
    ntp_log_complevel="9"

%common
    ntp_signal () {
        if [ -f "@l_prefix@/var/ntp/ntpd.pid" ]; then
            kill -$1 `cat @l_prefix@/var/ntp/ntpd.pid`
        fi
    }

%start -p 200 -u root
    opServiceEnabled ntp || exit 0
    #   synchronize local machine once at startup
    #   because ntpd does not skip large time offsets
    @l_prefix@/bin/ntpdate \
        `grep "^server" @l_prefix@/etc/ntp/ntp.conf |\
         awk '{ printf(" %s", $2); }'`
    opVarIsYes ntp_daemon || exit 0
    #   run the NTP daemon for continued synchronization
    @l_prefix@/bin/ntpd \
        -p @l_prefix@/var/ntp/ntpd.pid \
        -f @l_prefix@/var/ntp/ntpd.drift \
        -l @l_prefix@/var/ntp/ntpd.log \
        -s @l_prefix@/var/ntp/ntpd.stat/

%stop -p 200 -u root
    opServiceEnabled ntp && opVarIsYes ntp_daemon || exit 0
    ntp_signal TERM

%restart -u root
    opServiceEnabled ntp && opVarIsYes ntp_daemon || exit 0
    ntp_signal TERM
    sleep 2
    #   restart the NTP daemon for continued synchronization
    @l_prefix@/bin/ntpd \
        -p @l_prefix@/var/ntp/ntpd.pid \
        -f @l_prefix@/var/ntp/ntpd.drift \
        -l @l_prefix@/var/ntp/ntpd.log \
        -s @l_prefix@/var/ntp/ntpd.stat/

%hourly -u root
    opServiceEnabled ntp || exit 0
    opVarIsYes ntp_daemon && exit 0
    (
        sleep 30
        @l_prefix@/bin/ntpdate \
            `grep "^server" @l_prefix@/etc/ntp/ntp.conf |\
             awk '{ printf(" %s", $2); }'`
    ) >/dev/null &
        

%daily -u root
    opServiceEnabled ntp && opVarIsYes ntp_daemon || exit 0
    opTmpDirGen ntp
    opTmpDirFile ntp hint hintfile
    prolog="true"
    if [ ".$ntp_log_prolog" != . ]; then
        prolog="$prolog; $ntp_log_prolog"
    fi
    epilog="echo 'epilog' >$hintfile"
    if [ ".$ntp_log_epilog" != . ]; then
        epilog="$epilog; $ntp_log_epilog"
    fi
    shtool rotate -f \
        -n${ntp_log_numfiles} -s${ntp_log_minsize} \
        -d -z${ntp_log_complevel} \
        -o@l_musr@ -g@l_mgrp@ -m644 \
        -P "$prolog" \
        -E "$epilog" \
        @l_prefix@/var/ntp/ntpd.log
    if [ ".`cat $hintfile`" = ".epilog" ]; then
        ntp_signal TERM
        sleep 2
        #   restart the NTP daemon
        @l_prefix@/bin/ntpd \
            -p @l_prefix@/var/ntp/ntpd.pid \
            -f @l_prefix@/var/ntp/ntpd.drift \
            -l @l_prefix@/var/ntp/ntpd.log \
            -s @l_prefix@/var/ntp/ntpd.stat/
    fi
    opTmpDirDel ntp
