#!/usr/bin/perl -w -t

use LWP::UserAgent;
use HTTP::Date;
use POSIX qw(strftime);
use strict;

my $testonly=0;

my $url = $ARGV[0];
my $ua = new LWP::UserAgent(agent => "httpdate/0.1 ($^O)");
$ua->env_proxy();

die "Usage: $0 url\n" unless $url;

my $response = $ua->get($url);

die "Request failed: '".$response->status_line."'\n" unless $response->is_success;
die "No Date-header sent by server.\n" unless $response->header("Date");

my $gmt=str2time($response->header("Date"))."\n";

die "Date-header not wellformed!" unless defined($gmt);

print "Old time: ".gmtime()."\n";
print "New time: ".gmtime($gmt)."\n";
my $timestamp=strftime("%m%d%H%M%Y.%S",gmtime($gmt));

if($testonly)
{
  print "date -u $timestamp\n";
  print "hwclock --systohc\n";
}
else
{
  $ENV{"PATH"}="/bin:/usr/bin:/usr/sbin/";
  $ENV{"ENV"}="";
  system("date -u $timestamp");
  system("hwclock --systohc");
}

