#!/usr/bin/perl
# -*-perl-*-

#use strict;
#use diagnostics;

use Net::FTP;

use Debian::DpkgFtp;

# deal with arguments
my $vardir = $ARGV[0];
my $method = $ARGV[1];
my $option = $ARGV[2];

if ($option eq "manual") {
    print "Enter package file names or a blank line to finish\n";
    while(1) {
	print "Enter package file name:";
	my $fn = <STDIN>;
	chomp $fn;
	if ( $fn == "") {
	    exit 0;
	}
	if ( -f $fn ) {
	    system ("dpkg", "--merge-avail", $fn);
	} else {
	    print "Could not find $fn, try again\n";
	}
    };
};

#print "vardir: $vardir, method: $method, option: $option\n";

my $arch=`dpkg --print-installation-architecture`;
$arch='i386' if $?;
chomp $arch;
my $exit = 0;

# get info from control file
do "$vardir/methods/ftp/vars" or die "Could not find state file (re-run Access method)";

chdir "$vardir/methods/ftp";

print "Getting Packages files...(stop with ^C)\n\n";

my @pkgfiles;
my $ftp;
my $packages_modified = 0;

sub download {
    $ftp = do_connect ($::ftpsite,$::username,$::password,$::ftpdir,$::passive,
		       $::useproxy,$::proxyhost,$::proxylogname,$::proxypassword);

    my @dists = split(/ +/, $::distribs);
    my $dist;
    PACKAGE:
    foreach $dist (@dists) {
	my $dir = "$dist/binary-$arch";
	my $must_get = 0;
	my $newest_pack_date;

	# check existing Packages on remote site
	print "\nChecking for Packages file... ";
	$newest_pack_date = do_mdtm ($ftp, "$dir/Packages.gz");
	if (defined $newest_pack_date) {
	    print "$dir/Packages.gz\n";
	} else {
	    $dir = "$dist";
	    $newest_pack_date = do_mdtm ($ftp, "$dir/Packages.gz");
	    if (defined $newest_pack_date) {
		print "$dir/Packages.gz\n";
	    } else {
		print "Couldn't find Packages.gz in $dist/binary-$arch or $dist; ignoring.\n";
		next PACKAGE;
	    }
	}

	# we now have $dir set to point to an existing Packages.gz file

	# check if we already have a Packages file (and get its date)
	$dist =~ tr/\//_/;
	my @pack_stat = stat("Packages.$dist");
	# if not
	if (@pack_stat == ()) {
	    # must get one
#	    print "No Packages here; must get it.\n";
	    $must_get = 1;
	} else {
	    # else check last modification date

#	    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($newest_pack_date);
#	    print "Distant: " . $mday . "/" . $mon . "/" . $year . ", " . $hour . ":" . $min . ":" . $sec . "\n";
#	    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($pack_stat[9]);
#	    print "Local:   " . $mday . "/" . $mon . "/" . $year . ", " . $hour . ":" . $min . ":" . $sec . "\n";

	    if($newest_pack_date > $pack_stat[9]) {
#		print "Packages has changed; must get it.\n";
		$must_get = 1; 
	    } elsif ($newest_pack_date < $pack_stat[9]) {
		print " Our file is newer than theirs; skipping.\n";
	    } else {
		print " Already up-to-date; skipping.\n";
	    }
	}

	if ($must_get) {
	    -f "Packages.gz" and unlink "Packages.gz";
	    -f "Packages" and unlink "Packages";
	    my $size = 0;

	  TRY_GET_PACKAGES: 
	    while (1) {
		if ($size) {
		    print " Continuing ";
		} else {
		    print " Getting ";
		}
		print "Packages file from $dir...\n";
		eval {
		    if ($ftp->get("$dir/Packages.gz", "Packages.gz", $size)) {
			if (system("gunzip", "Packages.gz")) {
			    print "  Couldn't gunzip Packages.gz, stopped";
			    die "error";
			}
		    } else {
			print "  Couldn't get Packages.gz from $dir !!! Stopped.";
			die "error";
		    }
		};
		if ($@) {
		    $size = -s "Packages.gz";
		    if (yesno ("y", "Transfer failed at $size: retry at once")) {
			# maybe we could test if the old $ftp still works ?
			$ftp = do_connect ($::ftpsite,$::username,$::password,$::ftpdir,$::passive,
					   $::useproxy,$::proxyhost,$::proxylogname,$::proxypassword);
			if ($newest_pack_date != do_mdtm ($ftp, "$dir/Packages.gz")) {
			    print ("Packages file has changed !\n");
			    $size = 0;
			}
			next TRY_GET_PACKAGES;
		    } else {
			die "error";
		    }
		}
		last TRY_GET_PACKAGES;
	    }

	    if(!rename "Packages", "Packages.$dist") {
		print "  Couldn't rename Packages to Packages.$dist";
		die "error";
	    } else {
		# set local Packages file to same date as the one it mirrors
		# to allow comparison to work.
#		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime($newest_pack_date);
#		print "Setting mtime to: " . $mday . "/" . $mon . "/" . $year . ", " . $hour . ":" . $min . ":" . $sec . "\n";
		utime $newest_pack_date, $newest_pack_date, "Packages.$dist";
		$packages_modified = 1;
	    }
	}
	push @pkgfiles, "Packages.$dist";
    }
    $ftp->quit();
}

eval {
    local $SIG{INT} = sub {
	die "Interrupted!\n";
    };
    download();
};
if($@) {
    if($@ =~ /timeout/i) {
	print "FTP TIMEOUT\n";
    } else {
	print "FTP ERROR - $@\n";
    }
    $exit = 1;
};

my $ans;

if ($packages_modified) {	# don't clear if nothing changed
    print <<EOM;

It is a good idea to clear the available list of old packages.
However if you have only downloaded a Package files from non-main
distributions you might not want to do this.

EOM
    if (yesno ("y", "Do you want to clear available list")) {
	print "Clearing...\n";
	if(system("dpkg", "--clear-avail")) {
	    print "dpkg --clear-avail failed.";
	    die "error";
	}
    }
}

if (!$packages_modified) {
    print "No Packages files was updated.\n";
} else {
    my $file;

    foreach $file (@pkgfiles) {
	if(system ("dpkg", "--merge-avail", $file)) {
	    print "Dpkg merge available failed on $file";
	    $exit = 1;
	}
    }

    if(system("dpkg", "--forget-old-unavail")) {
	print "dpkg --forget-old-unavail failed";
	die "error";
    }
}
exit $exit;
