#!/usr/local/bin/perl
#
use strict;
use Net::FTP;
use Getopt::Std;
use Pod::Usage;
use Time::gmtime;
#
# set default values
#
my $ftp_ip = "192.168.0.212";
my $ftp_user = "netrsFTP";
my $ftp_pass = "gpsr";
my $current_only = 0;
#
# read command line arguments
#
# -c only check current files
# -h help
my %opts;
getopts("cmh", \%opts);
$current_only = 1 if (defined($opts{c}));
#
# check arguments
#
pod2usage(-exitstatus => 1, -msg => "Help requested") if (defined($opts{h}));
pod2usage(-exitstatus => 0, -verbose => 2) if (defined($opts{m}));
#
# connect to the server
#
print "Connecting to $ftp_user\@$ftp_ip\n";
my %ftp_opts;
$ftp_opts{'Passive'} = 0;
my $ftp = Net::FTP->new($ftp_ip,%ftp_opts);
die "Could not connect to $ftp_ip" if (!$ftp);
print "Logging in\n";
die "Could not login" if (!$ftp->login($ftp_user, $ftp_pass));
$ftp->binary();

print "Get top level directory\n";
my @response = $ftp->dir();
my @top_dirs;
my $dir;
foreach $dir (@response)
{
    if ($dir =~ m/^d.+ (\d\d\d\d\d\d)$/)
    {
        push @top_dirs,($1);
	if (! -d $1)
	{
	    print "mkdir $1\n";
	    mkdir $1;
	}
    }
}

print "Get 2nd level dirs\n";
my @second_dirs;
my $dir2;
foreach $dir (@top_dirs)
{
    @response = $ftp->dir($dir);
    foreach $dir2 (@response)
    {
        if ($dir2 =~ m/^d.+ (\d\d)$/)
	{
	    push @second_dirs,("$dir\/$1");
	    if (! -d "$dir/$1")
	    {
	        print "mkdir $dir/$1\n";
		mkdir "$dir/$1";
	    }
	}
    }
}

print "Get files\n";
my $file;
my $filename;
my $gm = gmtime();
my $djul_cur = djul($gm->year() + 1900, $gm->mon()+1, $gm->mday());
foreach $dir2 (@second_dirs)
{
    my $get_files = 1;
    if ($current_only)
    {
        $dir2 =~ m/(\d\d\d\d)(\d\d)\/(\d\d)/;
	my $djul_dir2 = djul($1,$2,$3);
	$get_files = 0 if ($djul_dir2 < $djul_cur-1);
    }
    if ($get_files)
    {
	@response = $ftp->dir($dir2);
	foreach $file (@response)
	{
	    if ($file =~ m/-.+ (\S+\.T00)$/)
	    {
		$filename = $1;
		if (! -f "$dir2/$filename")
		{
		    print "get $dir2/$filename\n";
		    $ftp->get("$dir2/$filename");
		    rename $filename,"$dir2/$filename";
		}
	    }
	}
    }
}

print "Bye.\n";
$ftp->quit();

sub djul {
    my $j=$_[0];
    my $m=$_[1];
    my $t=$_[2];
    my ($i,$k,$dj);

    if ($m <= 2) {
        $j=$j-1;
        $m=$m+12;
    }
    $i=int($j/100);
    $k=2-$i+int($i/4);
    $dj=int(365.25*$j)-679006.0;
    $dj=$dj+int(30.6001*($m+1))+$t+$k;

    return $dj;
}

__END__

=head1 NAME
netrs_mirror.pl - Script to get latest files from NetRS via FTP

=head1 SYNOPSIS

B<netrs_mirror.pl>
[B<-c>]
[B<-m>]
[B<-h>]

=head1 OPTIONS

=over 8

=item B<-c>

Only look for current files (within the last day)

=item B<-m>

Display man page for netrs_mirror.pl

=item B<-h>

Display help

=back

=head1 DESCRIPTION

Get latest files from NetRS FTP

=head1 EXAMPLES

=item netrs_mirror.pl -c

Looks for files wwithin the last day to download

=head1 AUTHOR

James Johns, UCAR/COSMIC

=cut


