#!/usr/bin/perl -w

# Based on work of Matthew.Stier@fnc.fujitsu.com
#
# Dobrica Pavlinusic <dpavlin@rot13.org>
# http://www.rot13.org/~dpavlin/sysadm.html
#
# Usage: parse_ntpq.pl host peer

use strict;

my $gInstallRoot;
BEGIN {
	$gInstallRoot = (($0 =~ m:^(.*/):)[0] || "./") . "..";
}


use lib "$gInstallRoot/lib";
use strict;

# Test for the number of arguments
if ($#ARGV != 1) {
	print STDERR "usage: $0 host [peer|--config]\n";
	exit 1;
}

# Get the server
my($server) = shift @ARGV;
# Get the peer
my($peer) = shift @ARGV;

my @targets;

# Get the ntpq data
open(NTPQ,"/usr/bin/ntpq -pn $server |") || die "ntpq: $!";

if ($peer eq "--config") {
	print "target --default--\n\tserver = $server\n\n";
}

my $skip_header = 1;
# Step through remaining lines
while (<NTPQ>) {
	chomp;
	next if (! /^=+$/ && $skip_header);
	$skip_header = 0;

	# Break lines into fields
	my($remote, $refid, $stratum, $t, $when, $poll, $reach, 
		$delay, $offset, $jitter) = (split ' ', substr($_, 1), 10);
	# Print delay, offset, and jitter
	print "$delay\n$offset\n$jitter\n" if ( $remote eq $peer );
	if ($peer eq "--config" && $reach && $reach > 0 && $remote ne "127.127.1.1") {
		print "target $server-$remote\n\tpeer = $remote\n\tskip-overview = 1\n\n";
		push @targets,"$server-$remote";
	}
}

if ($peer eq "--config") {
	print "target $server-overview\n\tmtargets  = \"",join("; ",@targets),"\"";
}
