#!/bin/sh
# Copyright (C) 2013-2016 Jeremy Chadwick. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# Waits for ntpc/ntpdate to properly sync time before starting up any
# daemons past this point. The way it works is by repeatedly calling
# /bin/date +%Y and seeing if the year returned is later than 1970.
# Most routers do not have battery-backed RTCs, so their clocks always
# start from the epoch (December 31st 1969). A year later than 1970
# (i.e. 1971 or later) would indicate ntpc has finished.
#
# This is helpful for daemons which are time-sensitive, such as
# BIND/named, where a clock that is extremely skewed can cause errors
# like: checkhints: unable to get root NS rrset from cache: not found
#
# TODO: Implement stop/start/restart/reconfigure/check/kill argument
# support, per rc.unslung. Right now this just runs blindly every
# time. stop/reconfigure/check/kill should be no-ops, start/restart
# should actually do something.
#
NAME="netwait[$$]"
INTERVAL=7
MAXCOUNT=13
checkdate() {
local year=$(/bin/date +%Y)
if [ $year -gt 1970 ]
then
return 0
fi
return 1
}
# First thing we do is check the current date. If the year is
# already compliant, then don't call logger or anything else; just
# exit cleanly immediately.
if checkdate; then
exit 0
fi
# Otherwise use a loop to check things repeatedly and bail out if
# things look good -- or bail out at the very end with a nastygram
# indicating we're not responsible if daemons misbehave past this
# point. :-)
i=1
while [ $i -le $MAXCOUNT ]
do
logger -t $NAME "Waiting for ntpc (attempt ${i}/${MAXCOUNT})"
sleep $INTERVAL
if checkdate; then
logger -t $NAME "Clock synced; good to go!"
exit 0
fi
i=$((i+1))
done
logger -t $NAME "Clock remains unsynced; continuing anyway"
exit 1