#!/usr/bin/perl -w 
package mirrors;

sub ver {print "
mirrors  version 1.01  2003/02/17
(C) Dirk Eddelbuettel 1998-2001 \<edd\@debian.org\>
(C) Ian Maclaine-cross 2003-2006 \<iml\@debian.org\>
You may use this only under the conditions of the
General Public Licence in file GPL.

";
exit 0;
};

sub use {print "Usage: $PROGRAM_NAME \[options\] -f file
Options:
        -d      verbose operation
	--help
        -h      this message
        -n max  maximum number of mirrors to show
	--version
        -v      version

        file    in $dir containing list of archive network
                FQDN including files for CPAN, CTAN and debian.
                You may add or edit FDQN list files in $dir.

$PROGRAM_NAME measures round trip time to Internet sites in ms for 
small ICMP packets using \"fping\". Download speed from site is 
highest for smallest trip time.
See: $PROGRAM_NAME (1), fping (1).
Example: $PROGRAM_NAME -f Debian
";
exit 0;
};

use strict;
use English;
use File::Basename;
use Getopt::Std;
use IPC::Open2;
use vars qw($opt_h $opt_f $opt_d $opt_n $opt_v);

$mirrors'dir = "/etc/mirror/sites/";
my $inputfile; 
my $max = 20;
$PROGRAM_NAME =~ s|.*/||;	# strip everything before last slash

&use if ! $ARGV[0];
for ( @ARGV ){
    &use if m/--help/; 
    &ver if m/--version/;
};
getopts('dhf:n:v') or die("Try `$PROGRAM_NAME -h` for help screen.\n");
&use if $opt_h or ! $opt_f;
&ver if $opt_v;

$max = $opt_n if ($opt_n);
print "Max is set to $max\n" if $opt_d;

$inputfile="$mirrors'dir$opt_f";
if( ! -f $inputfile ){
    die "File $inputfile does not exist.\n" unless -f $opt_f;
    $inputfile=$opt_f;
}

print "Measuring ping times to all Debian mirror sites. " if $opt_d;
print "Please be patient.\n" if $opt_d;
    
open(DATA, $inputfile) or die "Cannot open $inputfile\n";

open2("PINGOUT", "PINGIN", "fping -ae") or die "Cannot start fping(1)\n";

# Parse the FQDN list file 
my $state = 0;
while (<DATA>) {		# parse the file for ftp sites 
    next if (m/^\s*$/);		# skip empty lines
    next if (m/^\s*\#.*$/);	# skip comment lines
    my $mirror = $_;
    $mirror =~ s/\#.*$//;       # delete trailing comment
    if (defined($mirror)) {
	print "Pinging $mirror \n" if $opt_d;
	print PINGIN "$mirror\n"; 
    }
}
close(DATA);
close(PINGIN);

open2("SORTOUT", "SORTIN", "sort -n") or die "Cannot start sort(1)\n";

while (<PINGOUT>) {
    my ($mirror,$time) = ($ARG =~ m|^(\S*)\s*\((\d+\.?\d*) ms(ec)?\)|);
    print "fping reports $time for $mirror\n" if $opt_d;
    print SORTIN "$time $mirror\n";
}
close(SORTIN);
close(PINGOUT);

print( "\nTime (ms)    Site FQDN\n------------------------\n" );   
my $i=1;
while (<SORTOUT>)   {
    print "$_"; 
    last if ($i++ == $max);
}
close(SORTOUT);
