#!/usr/bin/perl

# kernel-check - by greenfly
# 
# this script will check for the latest file in a specified directory
# (or file glob) on any number of ftp servers

use strict;

use Net::FTP;

my $host;
my $ftp;
my $directory;
my $size;
my $date;
my $name;
my $latest;
my @files;
my %hosts;


# create an hash of arrays
@{$hosts{"ftp.kernel.org"}} = 
      (
      "/pub/linux/kernel/v2.4/linux*gz",
      "/pub/linux/kernel/v2.6/linux*gz",
      "/pub/linux/kernel/people/akpm/patches/2.6/2.6.0-test4"
      );

# to add another host, just do:
# @{$hosts{"some.other.host"}} =
#	(
#	"/path/to/directory/1/",
#	"/path/to/directory/2/",
#	);

foreach $host (sort keys %hosts)
{
   print "connecting to $host\n";
   $ftp = Net::FTP->new("$host", Debug => 0);
   $ftp->login("anonymous",'-anonymous@');
   foreach $directory (@{$hosts{$host}})
   {
      print "getting list of files from $directory\n";
      @files = sort by_date $ftp->dir($directory);
      $latest = pop @files;
      $latest =~ /^(..........)\s+(\d) (\w+)\s+(\w+)\s+(\d+) (\w\w\w\s+\d+\s+\S+) (.*)$/;
      ($size, $date, $name) = ($5, $6, $7);
      $name = strip_path($name);
      print "Latest is $name, updated $date\n\n";
   }
   $ftp->quit;
}


# this is a bit of kung fu to actually properly sort by the
# date information you are given in a dir command
sub by_date
{
   my $ayear;
   my $byear;
   my %months = (
      		"Jan" , 1,
		"Feb" , 2, 
		"Mar" , 3,
		"Apr" , 4,
		"May" , 5,
		"Jun" , 6,
		"Jul" , 7,
		"Aug" , 8,
		"Sep" , 9,
		"Oct" , 10,
		"Nov" , 11,
		"Dec" , 12
		);

   $a =~ /^(..........)\s+(\d) (\w+)\s+(\w+)\s+(\d+) (\w\w\w\s+\d+\s+\S+) (.*)$/;
   my $adate = $6;
   $b =~ /^(..........)\s+(\d) (\w+)\s+(\w+)\s+(\d+) (\w\w\w\s+\d+\s+\S+) (.*)$/;
   my $bdate = $6;

   my ($amon, $aday, $atime) = split /\s+/, $adate;
   my ($bmon, $bday, $btime) = split /\s+/, $bdate;
   $amon = $months{$amon};
   $bmon = $months{$bmon};

# if the time is actually a year, set the year
   if($atime =~ /\d\d\d\d/)
   {
      $ayear = $atime;
   }
# otherwise set the year to be the current year
   else
   {
      $ayear = (localtime)[5] + 1900;
   }
# if the time is actually a year, set the year
   if($btime =~ /\d\d\d\d/)
   {
      $byear = $btime;
   }
# otherwise set the year to be the current year
   else
   {
      $byear = (localtime)[5] + 1900;
   }

   $ayear <=> $byear
   ||
   $amon <=> $bmon
   ||
   $aday <=> $bday
   ||
   $atime <=> $btime

}



sub strip_path
{
   my $path = shift;
   $path =~ s/.*\///;
   return $path;
}
