#!/bin/sh

set -e

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

do_syncwithrtc ()
{
	$LOGGER "Sync with RTC" || :
	hwclock --rtc=/dev/rtc0 --systohc --utc --noadjfile
}

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

LOGGER="logger -t ntpsync"

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

if [ -e /tmp/ntp-sync.lock ]; then
	$LOGGER "other ntp sync proc execute. this proc exit."
	eixt
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 ] && [ -d /usr/sbin ]; then
	exit 0
fi

# ntp設定存在チェック
AILE_NTP_CONF=/opt/aile/config/ntp.conf
if [ ! -r $AILE_NTP_CONF ]; then
	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=}
		$LOGGER "ntpserver: $AILE_NTP_SERVER" || :
		;;
	*)
		;;
	esac
done
exec 3<&-

if [ -z $AILE_NTP_SERVER ]; then
	$LOGGER "SERVER option is invalid." || :
	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 ntpdate
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

# if ntpdate-debian -s $OPTS $AILE_NTP_SERVER 2>/dev/null ; then
 if ntpdate -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
	if [ -e /tmp/ntp-sync.lock ]; then
		$LOGGER "Other Ntp Proc Executing. No Ntp Time Sync."
	else
		$LOGGER "Set RTC to the current time" || :
		hwclock --rtc=/dev/rtc0 --systohc --utc --noadjfile
	fi
else
	$LOGGER "Failed to Sync with NTP Server." || :
	do_syncwithrtc
fi

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

$LOGGER "END" || :

)

### EOF ###