BEGIN {
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib");
}


use strict;
use util;


my $source_directory = "Z:\\";
my $target_directory = "C:\\mdewsnip\\CIC\\Images\\";


sub main
{
    # Find all the files in the source directory
    if (!opendir(DIR, $source_directory)) {
	die "Error: Couldn't read directory $source_directory\n";
    }
    my @directory_files = readdir(DIR);
    closedir(DIR);

    foreach my $directory_file (@directory_files) {
	next if ($directory_file eq "." || $directory_file eq "..");

	open(LOG, ">>log.txt");

	my $directory_file_path = &util::filename_cat($source_directory, $directory_file);
	print LOG "$directory_file_path ";
	if (-f $directory_file_path) {
	    print LOG "(File)\n";
	}
	else {
	    print LOG "(Directory)\n";
	    my $images_revised_directory = &util::filename_cat($directory_file_path, "images REVISED");
	    if (-e $images_revised_directory) {
		&copy_directory_to_local_drive($images_revised_directory);
	    }
	}

	close(LOG);
    }
}


sub copy_directory_to_local_drive
{
    my ($source_directory_path) = (@_);

    my $target_directory_path = $source_directory_path;
    my $source_directory_regexp = $source_directory;
    $source_directory_regexp =~ s/\\/\\\\/g;
    $target_directory_path =~ s/^$source_directory_regexp/$target_directory/;
    if (!-e $target_directory_path) {
	print LOG " Creating new folder $target_directory_path!\n";
        &util::mk_all_dir($target_directory_path);
    }

    # Find all the files in this directory
    if (!opendir(DIR, $source_directory_path)) {
	die "Error: Couldn't read directory $source_directory_path\n";
    }
    my @source_directory_files = readdir(DIR);
    closedir(DIR);

    foreach my $source_directory_file (@source_directory_files) {
	next if ($source_directory_file eq "." || $source_directory_file eq ".." || $source_directory_file eq "Thumbs.db");

	print LOG "  $source_directory_file ";

	my $source_directory_file_path = $source_directory_path . "\\" . $source_directory_file;
	my $target_directory_file_path = $target_directory_path . "\\" . $source_directory_file; 

	# File doesn't exist locally, so is new
	if (!-f $target_directory_file_path) {
	    print LOG "(New file, copying...)\n";
	    &util::cp($source_directory_file_path, $target_directory_file_path);
	}
	# File exists locally but file has changed
	elsif ((-s $source_directory_file_path) != (-s $target_directory_file_path)) {
	    print LOG "(File changed, copying...)\n";
	    &util::cp($source_directory_file_path, $target_directory_file_path);
	}
	# File is unchanged, so ignore
	else {
	    print LOG "(Unchanged)\n";
	}
    }
}


main(@ARGV);
