#!/usr/local/bin/perl

use LWP::Simple qw(mirror $ua);
use File::Copy

$| = 1;

$ua->timeout(60);

while(<STDIN>) {
  # Get filename and URL from Current Home: header in file
  chomp;
  $file = $_;
  open(IN, $file);
  my $url;
  while(<IN>) {

  	if (/^# Current\s+Home:\s+(http:[^\s]+)/) {
	$url = $1;
	last;
  	}
  }
  close(IN);

  # Back up current copy in case the fetch fails
  #print "$file: $url\n";
  unlink("backup/$file");
  rename("$file","backup/$file")||print "Cannot rename $file to backup/$file.\n";

  # Fetch the current copy from the URL
  $result = mirror($url, $file);
  print "$file\t$result\n";
  if ($result != 200) { 
    unlink("$file");
    rename("backup/$file","$file");
    print("Unsuccessful, restored old file.\n");
  }

  # Get Version of new copy
  open(IN, $file);
  my $newver;
  while(<IN>) {
  	if (/^#.*Version:\s+(\S+)/i) {
	$newver = $1;
	last;
  	}
  }
  close(IN);

  # Get Version of old copy
  my $oldfile = "../".$file;
  open(IN, $oldfile);
  my $oldver;
  while(<IN>) {
  	if (/^#.*Version:\s+(\S+)/i) {
	$oldver = $1;
	last;
  	}
  }
  close(IN);

  print pack("A35",$file)."\told=$oldver\tnew=$newver\n";

  # Update real copy if different version
  if (not $newver eq $oldver) {
    unlink("../backup/$file");
    rename("../$file","../backup/$file");
    copy("$file","../$file");
    print "Updated $file.\n";
  }

}

exit 0;
