#!/bin/sh

#TODO: Replace with valid import once changes to chrony package done

CONFIGFILE=/var/etc/chrony.conf
INCLUDEFILE=/etc/chrony/chrony.conf
SOURCEDIR=/var/chrony/source

SEQUENTIAL_MODE=0

handle_source() {
    local cfg=$1 sourcetype=$2 hostname minpoll maxpoll iburst ipversion

    hostname=$NTP_SOURCE_HOSTNAME
    [ -z "$hostname" ] && config_get hostname "$cfg" hostname
    [ -z "$hostname" ] && return
    config_get minpoll "$cfg" minpoll
    config_get maxpoll "$cfg" maxpoll
    config_get_bool iburst "$cfg" iburst 0
    config_get ipversion "$cfg" ipversion
    echo $(
        echo $sourcetype $hostname
        [ -n "$minpoll" ] && echo minpoll $minpoll
        [ -n "$maxpoll" ] && echo maxpoll $maxpoll
        [ "$iburst" = "1" ] && echo "iburst"
        [ "$ipversion" = "4" ] && echo "ipv4"
        [ "$ipversion" = "6" ] && echo "ipv6"
    )
}

device_to_interface_convert(){
    local intf=$2 __tmp
    __tmp=$(eval $(echo "ubus call network.interface dump | jsonfilter -e '@.interface[@.device=\"$intf\"].interface'"))
    export "$1=$__tmp"
    return 0
}

handle_allow() {
    local cfg=$1 iface

    config_get iface "$cfg" interface

    [ -z "$iface" ] && return
    echo allow $iface
}

handle_makestep() {
    local cfg=$1 threshold limit

    config_get threshold "$cfg" threshold
    config_get limit "$cfg" limit
    [ -z "$threshold" -o -z "$limit" ] && return
    echo makestep $threshold $limit
}

handle_maxsamples() {
    local cfg=$1 limit

    config_get limit "$cfg" limit
    [ -z "$limit" ] && return
    echo maxsamples $limit
}

reload_uci_config() {
    . /lib/functions.sh
    . /lib/functions/network.sh

    config_load chrony
    mkdir -p $(dirname $CONFIGFILE)

    (
        echo include $INCLUDEFILE
        echo sourcedir $SOURCEDIR
        if [ $SEQUENTIAL_MODE -eq 0 ]; then
            config_foreach handle_source server server
            config_foreach handle_source pool pool
            config_foreach handle_source peer peer
        fi
        config_foreach handle_allow allow
        config_foreach handle_makestep makestep
        config_foreach handle_maxsamples maxsamples
    ) > $CONFIGFILE
}


case $1 in
    chronyd_uci_seq_reload)
        SEQUENTIAL_MODE=1
        mkdir -p $SOURCEDIR
        reload_uci_config
        ;;

    chronyd_uci_reload)
        reload_uci_config
        ;;

    *)
        echo "Usage : $0 [chronyd_uci_reload|chronyd_uci_seq_reload]"
        ;;
esac
