#!/bin/sh

BBOX="/usr/local/bin/busybox"
NTPD_SYNC="/usr/bin/lnxntpd_sync"

[ -z "${NTP_SERVER1}" ] && NTP_SERVER1="ntp.aliyun.com"
[ -z "${NTP_SERVER2}" ] && NTP_SERVER2="ntp.lnxall.com"

systemd_disable() {
    systemctl stop "$1"     2>/dev/null
    systemctl disable "$1"  2>/dev/null
}

ntpdrtc_init() {
    if [ ! -x "${BBOX}" ] ; then
        if [ -x "/usr/bin/busybox" ] ; then
            BBOX="/usr/bin/busybox"
        elif [ -x "/bin/busybox" ] ; then
            BBOX="/bin/busybox"
        else
            echo "Error, no valid busybox executable found."
            sleep 15 ; exit 1
        fi
    fi
    export BIN_BUSYBOX="${BBOX}"

    systemd_disable ntp
    systemd_disable systemd-timesyncd
    if [ -x "/etc/init.d/sysntpd" ] ; then
        /etc/init.d/sysntpd stop
        /etc/init.d/sysntpd disable
    fi

    timedatectl show 2>/dev/null
    [ $? -eq 0 ] && timedatectl set-ntp false
    return 0
}

mainfunc() {
    echo "Updating system time from RTC device..."
    local OUTPUT="$(${BBOX} hwclock -r 2>/dev/null)"
    [ $? -eq 0 ] && [ -n "${OUTPUT}" ] && ${BBOX} hwclock -s

    echo "Starting busybox based NTP Server..."
    exec ${BBOX} ntpd -n -N -l -S ${NTPD_SYNC} -p "${NTP_SERVER1}" \
        -p "${NTP_SERVER2}" ${NTP_SERVER3:+-p} ${NTP_SERVER3} ${NTP_SERVER4:+-p} ${NTP_SERVER4}
}

ntpdrtc_init
mainfunc
exit 1
