#! /usr/bin/env perl

use Carp;
use warnings;
use strict;

use File::Basename;
use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
use Pod::Usage qw( pod2usage );


# Hard coded values
my $remote_root = '/scratch3/watersc1/';
my $host_iter = 0;
my @ipp_hosts   = ('166.122.172.41','166.122.172.42','166.122.172.43','166.122.172.44',
		   '166.122.172.45','166.122.172.46','166.122.172.47','166.122.172.48',
		   '166.122.172.49','166.122.172.50','166.122.172.51','166.122.172.52','166.122.172.53');
my @remote_hosts = ('mu-fe1.lanl.gov','mu-fe2.lanl.gov','mu-fe3.lanl.gov','mu-fe4.lanl.gov');
my $check_list;
my $transfer_list;
GetOptions(
    'check_list=s'  => \$check_list,
    'transfer_list=s' => \$transfer_list
    ) or pod2usage( 2 );

my @check_files = ();
my @transfer_files = ();

open(LIST,$check_list);
while(<LIST>) {
    chomp;
    push @check_files, $_;
}
close(LIST);
open(LIST2,$transfer_list);
while(<LIST2>) {
    chomp;
    push @transfer_files, $_;
}
close(LIST2);

unless ($#check_files == $#transfer_files) {
    die "The two lists are of unequal length.";
}

for (my $i = 0; $i <= $#check_files; $i++) {
    my $file = $check_files[$i];
    unless (-e $file) {
	print "$file\n";
	my $fetch_file = $transfer_files[$i];
	my $directory = dirname($file);
	unless (-d $directory) {
	    system("mkdir -p $directory");
	}
	
	scp_pull($fetch_file,$file);
    }
}

sub scp_pull {
    my $remote_file = shift;
    my $local_file = shift;
    
    my $host = $ipp_hosts[$host_iter];
    $host_iter++; 
    if ($host_iter > $#ipp_hosts) { $host_iter = 0; }
    system("scp ${host}:${remote_file} ${local_file}");
}
