#!/usr/bin/perl -w
use strict;
my $margin=50;
my $halfheight=612/2-$margin;
my $maxms=$halfheight/5; # We default to 5 points per ms
my $timewidth=86400;
my $graphwidth=792-2*$margin;
my $maxtime=0;
my @recent=();
my %offsets=();
my %badhost=();

sub parsefile($$) {
	my ($file,$timeoffset)=@_;
	my ($line,@line);

	open(LOG,"<",$file) or die "open($file): $!";
	while(defined($line=<LOG>)) {
		chomp $line;
		@line=split / /,$line;
		die $line unless(8==@line);
# day timeofday ip status offset delay dispersion jitter
		my $time=$line[1]+$timeoffset;
		my $ip=$line[2];
		$maxtime=$time if($maxtime<$time);
		$offsets{$ip}=[] unless($offsets{$ip});
		push @{$offsets{$ip}},[$time,$line[4]*1000];
		my $ms=abs($line[4]*1000);
		if($maxms<$ms and not $badhost{$ip}) {
			$badhost{$ip}=1;
			print STDERR "$ip has offset of over ${maxms}ms\n";
		}
		push @recent,$ip;
		shift @recent if(20<@recent);
	}
	close(LOG) or die "close: $!";
}

my @files=sort {$b cmp $a} glob "/var/log/ntpstats/peerstats.*";
die "unable to find peerstats log files" unless(@files);
parsefile($files[1],0);
parsefile($files[0],86400);

print <<"EOD";
%!PS-Adobe-3.0
%%Creator: parse-ntp-peerstats
%%Pages: 1
%%DocumentMedia: plain 612 792 0 () ()
%%BoundingBox: 0 0 612 792
%%LanguageLevel: 2
%%EndComments
%%BeginProlog
/transform {
	exch $timewidth div $graphwidth mul $margin add
	exch $maxms div $halfheight mul 306 add
} bind def
/m {transform moveto} bind def
/l {transform lineto} bind def
/host {
	setrgbcolor
	/Times-Roman 12 selectfont
	60 hosty moveto
	/hosty hosty 12 sub def
	show
} bind def
/rshow {dup stringwidth neg exch neg exch 2 copy rmoveto 3 2 roll show rmoveto} bind def
/shownum {
	/Times-Roman 9 selectfont
	dup 0 exch transform
	dup dup 612 $margin sub lt exch $margin gt and {
		gsave .75 setgray 2 copy moveto $graphwidth 0 rlineto stroke grestore
		exch 5 sub exch 3 sub moveto
		( ms) rshow
		11 string cvs rshow
	} {
		pop pop pop
	} ifelse
} bind def
%%EndProlog
%%Page: 1 1
%%PageOrientation: Landscape
612 0 translate 90 rotate
0 shownum
10 shownum
100 shownum
1000 shownum
-10 shownum
-100 shownum
-1000 shownum
0 0 transform pop $margin moveto
0 $halfheight 2 mul rlineto stroke
0 0 m
$timewidth 0 l
stroke
/hosty 612 $margin sub 12 sub def
EOD
my @colors=(
	"1 0 0",
	"0 1 0",
	"0 0 1",
	"0 1 1",
	"1 0 1",
	".85 .85 0",
	".5 .5 .5",
);
foreach my $ip (sort keys %offsets) {
	next unless(grep {$_ eq $ip} @recent);
	print "($ip) $colors[0] host\n";
	shift @colors if(1<@colors);
	my $op="m";
	for(my $i=0;$i<@{$offsets{$ip}};$i++) {
		my ($time,$offset)=@{$offsets{$ip}[$i]};
		$time-=$maxtime-$timewidth;
		next if($time<0);
		print "$time $offset $op\n";
		$op="l";
	}
	print "stroke\n";
}
print <<"EOD";
showpage
%%PageTrailer
%%Trailer
%%EOF
EOD
0;
