#!/usr/bin/perl
#written 28/03/2006 by Andrew Stringer
#This tests ntp servers listed in an xml file and checks the 
#stratum of each compared to the expected value in the config file.
#Also the reference time source for each server is displayed.

use Net::NTP;
use XML::Simple;
use Data::Dumper;
use warnings;
use strict;


MAIN:

my $configfile = '/data/rainsbrook/http/monitor/ntp-config.xml' ;
my $resultsfile = '/data/rainsbrook/http/monitor/ntp-monitor.html';
my $tmpresultsfile = '/data/rainsbrook/http/monitor/ntp-monitor.tmp';
my $url = 'http://192.168.5.11/monitor/ntp-monitor.html' ;
my $correctstratum ;

#set time
my $time = localtime;

#open file for html output
open (OUTPUTFILE, ">$tmpresultsfile") ;

#write out html header
print OUTPUTFILE <<ENDOFTEXT1 ;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Site NTP test stats.</title>
<meta http-equiv="refresh" content="30;URL=$url">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="Stylesheet" type="text/css" href="http://ns0.site.com/layout.css" />
    <!-- Disable IE6 image toolbar -->
<meta http-equiv="imagetoolbar" content="no" />
<link rel="icon" href="./favicon.ico" type="image/x-icon"
</head>

<body text="#000000" bgcolor="#ffffff" link="0000EE" vlink="#551A8B">
<div>
<a href="http://ns0.site.com/index.shtml">
<img src="http://ns0.site.com/bcclogo-ns0.png" class="logo" border="1" title="Back to ns0.site.com" height="76" 
width="429" />

</a>
</div>

<div class="box">
<h5>NTP status</h5>
<div class="body">
Last updated at $time

<br>
<!--start of results table-->
<table border = "1">
<tr>
<th>NTP server</th>
<th>stratum</th>
<th>RCI</th>
<th>TransmitTimestamp</th>
</tr>

ENDOFTEXT1


#read in config file
my $config = XMLin($configfile);

foreach my $e (@{$config->{server}})
{
        my $address = $e->{address};
        my $targetstratum = $e->{targetstratum};

        #get ntppacket
        my %ntppacket = get_ntp_response($address);

        my $stratum=$ntppacket{Stratum} ;
        my $rci = $ntppacket{'Reference Clock Identifier'} ;
        my $trt = $ntppacket{'Transmit Timestamp'};

        if ($stratum <= $targetstratum)
        {
        $correctstratum = '#00ff00' ;
        }
        else {
        $correctstratum = '#ff0000' ;
        }

print OUTPUTFILE <<ENDOFTEXT2 ;
        <tr>
        <td>$address</td>
        <td bgcolor="$correctstratum">$stratum ($targetstratum)</td>
        <td>$rci</td>
        <td>$trt</td>
        </tr> \n
ENDOFTEXT2

#end of foreach loop
}

print OUTPUTFILE <<ENDOFTEXT3 ;
</table>
RCI == Reference Clock Identifier
</div>
</div>

</body>
</html>

ENDOFTEXT3
close OUTPUTFILE ;


#copy tmp file to result file and change perms
`mv $tmpresultsfile $resultsfile`;
`chmod a+r $resultsfile` ;

exit (0);

