#!/usr/bin/perl -w

use strict;
use Net::NTP;

my $set_option = 0;
if ($ARGV[0] and $ARGV[0] eq '-s') {
	$set_option = 1;
	shift(@ARGV);
}
my $host = shift(@ARGV) or die "Usage: $0 [-s] ntpserver\n";

$Net::NTP::TIMEOUT = 20;

my %pkt = get_ntp_response($host);
# we should use Time::HiRes to get fractional seconds
# but Puppy Linux doesn't have this, maybe later
my $time_then = $Net::NTP::CLIENT_TIME_SEND;
my $time_now = $Net::NTP::CLIENT_TIME_RECEIVE;

my $receive_time = $pkt{'Receive Timestamp'};
my $transmit_time = $pkt{'Transmit Timestamp'};
my $round_trip_time = $time_now - $time_then - ($transmit_time - $receive_time);
my $estimated_time = $transmit_time + $round_trip_time / 2.0;

if ($set_option) {
	# ideally we should use adjtime(3) through Perl's syscall interface
	# maybe later when we really have fractional second resolution
	#
	# system("date -u -s \@$estimated_time");
	# doesn't work on Puppy Linux so we have to do it this way
	my @time_arr = gmtime($estimated_time);
	my $date_string = sprintf("%02d%02d%02d%02d%04d.%02d",
		$time_arr[4] + 1, $time_arr[3],
		$time_arr[2], $time_arr[1],
		$time_arr[5] + 1900, $time_arr[0]);
	system("date -u $date_string");
} else {
	print scalar localtime($estimated_time), "\n";
}
__END__

=head1 NAME

ntpset - set system clock using NTP

=head1 SYNOPSIS

ntpset [-s] ntpserver

=head1 ABSTRACT

Display or set the time obtained by NTP

=head1 DESCRIPTION

This program contacts the specified host, obtains the time and displays
it.  If the -s option is specified, it sets the system clock instead.

=head1 INSTALLATION

Copy the NTP.pm module to the appropriate site_perl directory of your
operating system so that it can be found by C<use Net::NTP;>.
This is probably:

C</usr/lib/perl5/site_perl/>I<perl_version/arch>C</Net/NTP.pm>

You need to edit C</etc/services> to contain the line:

C<ntp 123/udp>

if it doesn't already.

Then install ntpset anywhere convenient in your PATH.

=head1 SEE ALSO

ntpdate(1)

=head1 AUTHOR

Ken Yap <ken_yap_aus ATSIGN yahoo PERIOD com>

Code for NTP.pm taken from Net::NTP by James G. Willmore and slightly
modified to use older Socket API instead of IO::Socket, because the
latter doesn't work under Puppy Linux. I have included the entire
package as distributed by cpan.org so that you have the original NTP.pm
should you wish to consult it.

=head1 COPYRIGHT AND LICENSE

Copyright 2007 by Ken Yap

This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. 

=head1 CHANGE LOG

2007-08-02 Version 0.1

2007-08-03 Version 0.2 Fixed up error in sign of single trip time

=cut
