#! /usr/bin/perl -w

die "perl5 needed\n" unless ($] > 5);

use Getopt::Std;

$opt_n = 1000;			# How many tries before we give up? (10 min+)
$opt_s = 6;			# Seconds to sleep between tries (6s = 10/min)
$opt_v = 0;			# Be verbose?

getopts('n:s:v');

$cmd = 'ntpq -c "rv 0"';

$| = 1;				# Autoflush output.

print "Waiting for ntpd to synchronize...  " if ($opt_v);
for ($i = 0; $i < $opt_n; ++$i) {
    open(Q, $cmd." 2>&1 |") || die "Can't start ntpq: $!";
    while(<Q>) {
      chomp;
      # the first line should be similar to:
      # associd=0 status=0645 leap_none, sync_ntp, ...
      if (/^associd=0 status=(\S{4}) (\S+), (\S+),/) {
	my $status = $1;
	my $leap = $2;
	my $sync = $3;
	# print $_;
	# print "status <$status>, leap <$leap>, sync <$sync>\n";
	last if ($leap =~ /(sync|leap)_alarm/);
	if ($leap =~ /leap_(none|((add|del)_sec))/) {
	  # We could check $sync here to make sure we like the source...
	  print "\bOK!\n" if ($opt_v);
	  exit 0;
	}
	print "\bUnexpected 'leap' status <$leap>\n";
	exit 1;
      }

      if (/Connection refused/) {
	print "\bntpd is not running!\n" if ($opt_v);
	exit 1;
      }

      # Otherwise, we have a bigger problem.
      print "\bUnexpected first line <$_>\n";
      exit 1;
    }
    close(Q);
    print "\b".substr("*+:.", $i % 4, 1) if ($opt_v);
    sleep($opt_s);
}
print "\bNo!\nntpd did not synchronize.\n" if ($opt_v);
exit 1;
