#!/usr/bin/perl
use strict;


# +-------------------------
# | readFile(filename[,error_ref])
# |
# | returns the complete file contents
# |
# |
# |     in: filename -- name (path) of file to read
# |
# | return: one long string with the whole file, or
# |         empty string if no such file or empty file.
# |
# |         (use Perl's -e if you really really care whether
# |         the file was there...)
# |

sub readFile($;$)
  {
  my ($filename,$error_out) = (@_);
  my $bunch;
  my $file_contents;
  my $did;

  # (return error if ref provided)

  if($error_out)
    {
    $$error_out = (-f $filename) ? 0 : -1;
    }

  # (read the whole file, if present. else "")

  if(open(FILE,$filename))
    {
    binmode FILE;    # Bite me, Windows! --dvb
    while(read(FILE,$bunch,32000))
      {
      $file_contents .= $bunch;
      }
    close FILE;
    }

  return $file_contents;
  }


# -----------------------
# writeFile(filename,contents)
#
# creates new file and writes entire
# file contents. Return "ok" if so,
# or "" if not.
#
# |
# |     in: filename -- name of file to create (or replace)
# |         contents -- string of all the bytes to put into file
# |
# | return: 0 for success, <0 for error
# |

sub writeFile($$)
  {
  my ($filename,$contents) = (@_);

  my $did;

  #
  # If filename is "", print it to stdout
  # and that is all.
  #

  if($filename eq "")
    {
    print $contents;
    return "";
    }

  #
  # Delete existing file, if any.
  #

  unlink ($filename) if(-e $filename);

  $did = open(FILE,">$filename");
  if($did)
    {
    binmode FILE;    # Bite me, Windows! --dvb
    $did = print FILE $contents;
    close FILE;
    return $did ? 0 : -1;
    }

  return -1;
  }





my $gSourceBase = "/Volumes/lux";
my $gDestBase = "";

sub copyEm()
{
	my $text = readFile("files_list.txt");
	print $text;
	my @files = split(/\n/,$text);
	print "files: ",scalar(@files),"\n";
	foreach my $file (@files)
	{
		if($file =~ /^#.*$/)
		{
			next;
		}

		my $source = $gSourceBase.$file;
		my $dest = $gDestBase.$file;

		my $hasSource = -f $source? 1 : 0;
		my $hasDest = -f $dest? 1 : 0;

		print "$hasSource $hasDest $file\n";
		if($hasSource && !$hasDest)
		{
			my $destDir;
			$destDir = $1 if($dest =~ /^(.*)\/.*?$/);
			my $cmd1 = "mkdir -p $destDir";
			print "$cmd1\n";
			system($cmd1);
			my $cmd2 = "cp $source $dest";
			print "$cmd2\n";
			system($cmd2);
		}
	}
}


copyEm();

		
