#!/bin/sh
#
# ntpd plugin
#
# Author: Shun-ichi TAHARA <jado@flowernet.gr.jp>
# Time-stamp: <04/03/09 14:12:33 jado@sheira>
#

# *** Please change below as suitable ***
NTPCONF=/etc/ntp.conf

# Additional settings going into /etc/network.conf:
#
# NTP : NTP timeserver list [+ (from DHCP)|IPaddr...]

NTPDEV=$PLUGINSTATE/ntpd.devices

ntp_update ()
{
    killall ntpd > /dev/null 2>&1

    /usr/bin/sed -e '/# The rest is added by Planet.../,$d' $NTPCONF > $NTPCONF.N
    echo "# The rest is added by Planet..." >> $NTPCONF.N
    if [ ! -s $NTPDEV ]; then
	echo -en "server 127.127.1.0 prefer\nfudge 127.127.1.0\n" >> $NTPCONF.N
    else
	NTPS=`grep -v '^#' $NTPDEV | sort | uniq`
	for s in $NTPS; do
	    echo "server $s" >> $NTPCONF.N
	done
	if [ -x /usr/bin/ntpdate ]; then
	    /usr/bin/ntpdate $NTPS
	    /sbin/hwclock --systohc > /dev/null 2>&1
	fi
    fi
    mv $NTPCONF.N $NTPCONF

    if [ -x /usr/bin/ntpd ]; then
	/usr/bin/ntpd > /dev/null 2>&1
    else
	echo "Please install ntpd to work with NTP."
    fi
}

# Variables definition

ntpd_VARS="NTP:ntp_servers"

# Script on beginning

ntpd_begin ()
{
    return
}

# Script on starting

ntpd_start ()
{
    # Update ntpd stuff
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $NTPDEV > $NTPDEV.N
    if [ -n "$NTP" ]; then
	echo "# $1 begin" >> $NTPDEV.N
	for s in $NTP; do
	    echo "$s" >> $NTPDEV.N
	done
	echo "# $1 end device" >> $NTPDEV.N
    fi
    mv $NTPDEV.N $NTPDEV
    ntp_update
}

# Script on ending

ntpd_end ()
{
    return
}

# Script on stopping

ntpd_stop ()
{
    # Reset ntpd stuff
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $NTPDEV > $NTPDEV.N
    mv $NTPDEV.N $NTPDEV
    ntp_update
}
