#!/bin/sh
#
# ntpd plugin
# Author: Shun-ichi TAHARA <jado@flowernet.gr.jp>
# Time-stamp: <04/10/18 13:14:08 jado@sheira>
#
# Copyright (c) 2004 Shun-ichi TAHARA
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#

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

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

NTPDDEV=$PLUGINSTATE/ntpd.devices

ntpd_check ()
{
    if [ -s $NTPDDEV -o -s $NTPDDEV.N ]; then
	echo "others"
    else
	echo "offline"
    fi
}

ntpd_update ()
{
    local NTPS=

    if [ ! -x /usr/bin/ntpd -o ! -r $NTPDCONF ]; then
	echo "Please install and setup ntpd to work with NTP."
	return
    fi

    /usr/bin/sed -e '/# The rest is added by Planet.../,$d' \
	$NTPDCONF > $NTPDCONF.N
    echo "# The rest is added by Planet..." >> $NTPDCONF.N

    if [ -s $NTPDDEV ]; then
	NTPS=`/usr/bin/grep -v '^#' $NTPDDEV | sort | uniq`
	for s in $NTPS; do
	    echo "server $s" >> $NTPDCONF.N
	done
    else
	echo "server 127.127.1.0 prefer" >> $NTPDCONF.N
	echo "fudge 127.127.1.0" >> $NTPDCONF.N
    fi
    mv $NTPDCONF.N $NTPDCONF

    if [ "$1" = "offline" ]; then
	if [ -z "`pidof ntpd`" ]; then
	    /usr/bin/ntpd > /dev/null 2>&1
	fi
	return
    fi

    killall ntpd > /dev/null 2>&1

    if [ -x /usr/bin/ntpdate -a -n "$NTPS" ]; then
	/usr/bin/ntpdate $NTPS
	/sbin/hwclock --systohc > /dev/null 2>&1
    fi

    /usr/bin/ntpd > /dev/null 2>&1
}

# Variables definition

ntpd_VARS="NTP:ntp_servers"

# Script on starting

ntpd_start ()
{
    touch $NTPDDEV
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $NTPDDEV > $NTPDDEV.N

    if [ -n "$NTP" ]; then
	echo "# $1 begin" >> $NTPDDEV.N
	for s in $NTP; do
	    echo "$s" >> $NTPDDEV.N
	done
	echo "# $1 end device" >> $NTPDDEV.N
    fi

    local MODE=`ntpd_check`
    mv $NTPDDEV.N $NTPDDEV
    ntpd_update $MODE
}

# Script on stopping

ntpd_stop ()
{
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $NTPDDEV > $NTPDDEV.N

    local MODE=`ntpd_check`
    mv $NTPDDEV.N $NTPDDEV
    ntpd_update $MODE
}
