#!/bin/sh

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin

do_syncwithrtc ()
{
	$LOGGER "Sync with RTC" || :
	. /etc/default/rcS
	[ "$UTC" = "yes" ] && tz="--utc" || tz="--localtime"
	[ "$BADYEAR" = "yes" ] && badyear="--badyear"
	#hwclock --systz $tz --noadjfile $badyear || :
	hwclock --hctosys $tz --noadjfile $badyear || :

	#$LOGGER "Sync with RTC." || :
	##echo "Sync with RTC."
	#/opt/aile/syncClock
}

if [ $# -ge 1 ]; then
	OPTS="-b"
else
	OPTS="-B"
fi

# This is a heuristic:  The idea is that if a static interface is brought
# up, that is a major event, and we can put in some extra effort to fix
# the system time.  Feel free to change this, especially if you regularly
# bring up new network interfaces.
if [ "$METHOD" = static ]; then
	OPTS="-b"
fi

if [ "$METHOD" = loopback ]; then
	exit 0
fi

# Check whether ntpdate was removed but not purged; it's useless to wait for 
# it in that case.
if [ ! -x /usr/sbin/ntpdate-debian ] && [ -d /usr/sbin ]; then
	exit 0
fi

LOGGER="/usr/bin/logger -t ntpsync"
# ntp設定存在チェック
AILE_NTP_CONF=/opt/aile/config/ntp.conf
if [ ! -r $AILE_NTP_CONF ]; then
	#$LOGGER "Sync with RTC." || :
	#echo "Sync with RTC."
	#/opt/aile/syncClock
	do_syncwithrtc
	exit 0
fi

AILE_NTP_SERVER=
exec 3< $AILE_NTP_CONF
while read AILE_NTP_SERVER_TMP 0<&3
do
	case $AILE_NTP_SERVER_TMP in
	SERVER=*)
		AILE_NTP_SERVER=${AILE_NTP_SERVER_TMP#SERVER=}
		#echo "ntpserver: $AILE_NTP_SERVER"
		$LOGGER "ntpserver: $AILE_NTP_SERVER" || :
		;;
	*)
		;;
	esac
done
exec 3<&-

if [ -z $AILE_NTP_SERVER ]; then
	$LOGGER "SERVER option is invalid." || :
	#echo "SERVER option is invalid."
	#/opt/aile/syncClock
	do_syncwithrtc
	exit 0
else
	$LOGGER "sync with $AILE_NTP_SERVER..." || :
fi

(

# This is for the case that /usr will be mounted later.
if [ -r /lib/udev/hotplug.functions ]; then
	. /lib/udev/hotplug.functions
	wait_for_file /usr/sbin/ntpdate-debian
fi

LOCKFILE=/var/lock/ntpdate-ifup

# Avoid running more than one at a time
if [ -x /usr/bin/lockfile-create ]; then
	lockfile-create $LOCKFILE
	lockfile-touch $LOCKFILE &
	LOCKTOUCHPID="$!"
fi

invoke-rc.d --quiet ntp stop >/dev/null 2>&1 || true

#/usr/sbin/ntpdate-debian -t 0.2 -s $OPTS $AILE_NTP_SERVER 2>/dev/null || :
if /usr/sbin/ntpdate-debian -s $OPTS $AILE_NTP_SERVER 2>/dev/null ; then
	$LOGGER "SUCCESS" || :
	NTPDATE_EXIT_STATUS=0
else
	$LOGGER "FAILED" || :
	NTPDATE_EXIT_STATUS=1
fi

invoke-rc.d --quiet ntp start >/dev/null 2>&1 || true

if [ $NTPDATE_EXIT_STATUS -eq 0 ]; then
	$LOGGER "Set RTC to the current time" || :
	. /etc/default/rcS
	[ "$UTC" = "yes" ] && tz="--utc" || tz="--localtime"
	[ "$BADYEAR" = "yes" ] && badyear="--badyear"
	hwclock --rtc=/dev/rtc0 --systohc $tz --noadjfile $badyear || :
else
	$LOGGER "Failed to Sync with NTP Server." || :
	#echo "Failed to Sync with NTP Server. Sync with RTC."
	#/opt/aile/syncClock || :
	do_syncwithrtc
fi

if [ -x /usr/bin/lockfile-create ] ; then
	kill $LOCKTOUCHPID
	lockfile-remove $LOCKFILE
fi

$LOGGER "END" || :

) &
