# This  script  will copy the whole  source directory  tree
# to the  destination. Be carefull  that if the root target
# ( destination ) directory does not exists then it will be
# created. This script will work only on Windows platforms,
# but with some  small changes  will work on unix  as well.
# The destination files will be over  writen if they exist.
# George Bouras
# root@novastar.dtdns.net

my $source_directory = 'f:/temp' ;
my $target_directory = 'c:/temp' ;

&xcopy($source_directory,$target_directory);

############# xcopy subroutine #############

sub xcopy {
  my ($pwd,$i)=($_[0],$i++);
  die "You have not defined the \$target_directory variable, sorry...\n" 
    unless -e $target_directory ;
  die "You have not defined the \$source_directory variable, sorry...\n" 
    unless -d $source_directory;
  if (! -d $target_directory && -e $target_directory) {
    die "Can't continue because a file has target's dir name\n";
  } elsif ( ! -e $target_directory ) {
    mkdir $target_directory || die "Couldn't create dir : $target_node\n";
  }
  opendir ($i,$pwd) || die "Can't list $pwd\n";
  while (my $source_node=readdir $i) {
    next if $source_node=~/^\.*$/;
    $source_node       = $pwd.'/'.$source_node;
    ( my $relative_node ) = $source_node =~/$source_directory(.*)/;
    $target_node       = $target_directory.$relative_node;
    if (-d $source_node) {
      if (! -d $target_node && -e $target_node ) {
        die "Can't mkdir $target_node because a same name file exist\n";
      } elsif ( ! -e $target_node ) {
        print "mkdir  $target_node\n";
        mkdir $target_node || die "Couldn't create dir : $target_node\n";
      }
    } else {
      if ( -d $target_node && -e $target_node) {
        warn "Can't copy $target_node because a same name dir exist\n";
      } else {
        print "coping $source_node to $target_node\n" unless -e $target_node;
        (my $copy_target_node) = $target_node; $copy_target_node=~s/\//\\/g  ;
        (my $copy_source_node) = $source_node; $copy_source_node=~s/\//\\/g  ;
        `$ENV{ComSpec} /c copy /b $copy_source_node $copy_target_node`;
      }
    }
    &xcopy($source_node) if -d $source_node;
  }
  closedir $i;
}


