#!/bin/sh

# Monitor NTP drift

# Copyright (C) 2003-2006 IBM
#
# 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.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

if [ -z "$NTP_SERVER" -o "$NTP_SERVER" == "0" ]; then
	echo "NTP server is not configured."
	exit 255
fi

# NTP server is set in libpounder.sh
# Check NTP server every 15 seconds.  Evil, I know.
FREQ=15
# Threshold at which we warn about excessive drift
DWT=100
# Threshold at which we fail the test because of drift
DFT=500

LOGFILE=/proc/$$/fd/1

# Why do we need this?  Output is already being logged!
cp -f $LOGFILE $POUNDER_TMPDIR/ntpdrift-$$

# Do we have a python interpreter?
PYTHON=`which python`
if [ -n "$PYTHON" -a -x "$PYTHON" ]; then
		$POUNDER_HOME/timed_loop 900 "$POUNDER_SRCDIR/time_tests/drift-test.py" $NTP_SERVER $FREQ
else
	echo "There is no python interpreter installed.  Aborting."
	exit -1
fi

# Did drift-test.py fail to run properly?
if [ $? -ne 0 ]; then
	exit 1
fi

# Did we see any failures in actual drift test?
ERRORS=0
cp -f $LOGFILE $POUNDER_TMPDIR/ntpdrift2-$$
diff -u $POUNDER_TMPDIR/ntpdrift-$$ $LOGFILE | while read a b c d e field drift garbage; do
	if [ "$field" != "drift:" ]; then
		continue;
	fi
	drift=`echo $drift | awk -F "." '{print $1}'`
	if [ $drift -gt $DFT -o $drift -lt -$DFT ]; then
		echo ERROR: drift exceeded $DFT ppm: $a $b \
		$c $d $e $field $drift $garbage
		ERRORS=$((ERRORS + 1))
	elif [ $drift -gt $DWT -o $drift -lt -$DWT ]; then
		echo WARNING: drift exceeded $DWT ppm: $a $b \
		$c $d $e $field $drift $garbage
	fi
done

exit $ERRORS