#!/bin/sh

# It could take up to 30 seconds before the network adapter is receiving
# packets... Have no idea why, but this loop will try many times until
# ntpd-server is contacted. Make sure /etc/resolv.conf[.def] is set and
# points to a working nameserver.

DEFAULT=/etc/conf.d/ntpclient
[ -f $DEFAULT ] && . $DEFAULT

[ -z "$NTPHOST" ] && NTPHOST="pool.ntp.org" 

case "$1" in
start)
    NR=0
    while [ $NR -lt 10 ]; do
        # Try to ping... it will probably start some network activity.
        ping ${NTPHOST}
        LINK=`ethtool eth0 | grep -i "Link detected" | awk '{print $3;}'`
        if [ "${LINK}" != "yes" ]; then
                # No use to try if there are no link on eth0
                exit 0
        fi
        NRBYTES=`grep eth0 /proc/net/dev | awk '{print $2;}'`
        if [ "${NRBYTES}" != "0" ]; then
                # No use to try until there are some received packets
                ntpclient -i 2 -s -h ${NTPHOST}
        fi
        if date | grep -v 1970 >/dev/null 2>&1; then
                #exit when date is set (changed from 1970)
                exit 0
        fi
        NR=`expr $NR + 1`
        sleep 5
    done
    # another simple way would be this row.
    # ( sleep 30 ; ntpclient -i 3 -s -h ${NTPHOST} ) &
        ;;
stop)
        exit 1
        ;;
*)
        echo >&2 "Usage: $0 start|stop"
        exit 1
esac

exit 0
