#!/usr/local/bin/perl
# 
# $Header: emdb/sysman/admin/scripts/readJarStream.pl /st_emdbsa_11.2/1 2009/01/27 16:16:49 mmootha Exp $
#
# readJarStream.pl
# 
# Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
#
#    NAME
#      readJarStream.pl - <one-line expansion of the name>
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    rimmidi     07/30/08 - Code slap from 10205 to 11.2 DB Control
#    rimmidi     07/30/08 - Creation
#

use strict;
use File::Path;
my $jarCmd = shift(@ARGV);
my $sourceFiles = shift(@ARGV);
my $destFiles = shift(@ARGV);
my $overWriteFlag = shift(@ARGV);
my $backupFlag = shift(@ARGV);
my $isWindows=0;
my $os= `ver`;
if($os =~ "Microsoft")
{
  $isWindows = 1;
}
my $fileSep = "/";
if ($isWindows eq 1)
{
         $fileSep="\\";
}

my $sourcedir;
my $targetdir;
my $tmpFileName;
my $fileName;
#print $sourceFiles;

my @sourceFileArray = split(';',$sourceFiles);
my $numofSrcJars = @sourceFileArray;

my @destFileArray = split(';',$destFiles);
#print "destdir:$destFiles";
my $numofDestFiles = @destFileArray;
#print "num of dest files:$numofDestFiles";

#validate destination directories pre-exist,if not throw error

foreach my $destdr (@destFileArray)
{

  if (-d $destdr)
  {;}
  else
  {
       $destdr = substr($destdr,0,rindex($destdr,$fileSep));
  }
  if (-d $destdr)
  {;}
  else
  {
    print "Error: Destination: $destdr does not exist"; 
    exit;
  }
  
}

  my $dirCnt = 0;
  my $destDir = $destFileArray[$dirCnt];

  if (-d $destDir)
  {
    #ignore
  }
  else
  {
       $destDir = substr($destDir,0,rindex($destDir,$fileSep));
  }
  
#  my $savedJar = $destDir.$fileSep."grpcpy.jar";
#  print $savedJar;
#  print "\n";
#  print $destDir;
  chdir($destDir) or die "Can not find Destination Directory:$destDir";
  my $tmpdirName = time."emtmp";
  mkdir $tmpdirName or die "Could not create temp files: $!";
  chdir($tmpdirName); 
  binmode STDIN;
  open SPOOLER ,"| $jarCmd -x" or die "Can't fork: $!";
  binmode SPOOLER;
  local $SIG{PIPE} = sub { die "spooler pipe broke" };
  my $BUFSIZE = 32768;
  my $data;
  my $bytes;
  while(($bytes = read(STDIN, $data, $BUFSIZE)) > 0)
  {
    print SPOOLER $data;
  }
  close SPOOLER or die "bad spool: $! $?";

#get the metadata file name

opendir(DIR,$destDir.$fileSep.$tmpdirName);
my @files = grep(/em_grp_cpy.dat$/,readdir(DIR));
closedir(DIR);
my $metaFile;
foreach my $file (@files) 
{
 $metaFile = $file; 
}
#print "META FILE NAME:$metaFile";
open(METAFILE, "< $metaFile" ) or die "Can't open $metaFile : $!";
my @metadataarray = ();
while(my $content = <METAFILE> )
{
   chomp($content);
   push(@metadataarray,$content);
#   print "$content*";
}
close(METAFILE);
#process meta data in order

for (my $idx=0;$idx <= $numofDestFiles-1; $idx++)
{
#print "idx:$idx|";
my @metadata=split(";",$metadataarray[$idx]);
# print "metadatafilename:.$metadata[0]";
# print "metadatatype:".$metadata[1]."*";


   if ($metadata[1] eq 'FIL')
   {
      if (-d $destFileArray[$idx])
      { 
         my $filNme = $destFileArray[$idx].$fileSep.$metadata[0];

        if (-e $filNme)
        {
          if ($overWriteFlag eq "YES")
          { 
             my $bakfilNme = $destFileArray[$idx].$fileSep.$metadata[0].".bak";


             if ($backupFlag eq "YES")
             {
              rename($filNme,$bakfilNme);
              }
               rename($metadata[0],$filNme) or print "\n Could not move $metadata[0] to $destFileArray[$idx] : $!"; 
              if (-e $filNme)
              {
                print "\n Copied $sourceFileArray[$idx] successfully to $filNme";
              }
               
          } 
          else
           {
                #remove as the file no longer needed in tmpdir
                print"\n Overwrite is not selected,hence skipped copying $sourceFileArray[$idx] to $filNme as $filNme exists";
                unlink($metadata[0]);
           }
     
        }
        else
        {
               rename($metadata[0],$destFileArray[$idx].$fileSep.$metadata[0]) or print "\n Could not move $metadata[0] to $destFileArray[$idx] : $!"; 

              if (-e $filNme)
              {
                print "\n Copied $sourceFileArray[$idx] successfully to $filNme";
              }
        }
      }
      else
      {

        if (-e $destFileArray[$idx])
        {
          if ($overWriteFlag eq "YES")
          { 
             my $bakfilNme = $destFileArray[$idx].".bak";
             if ($backupFlag eq "YES")
             {
                 rename($destFileArray[$idx],$bakfilNme);
             }
                 rename($metadata[0],$destFileArray[$idx]) or print "\nCan not move $metadata[0] to $destFileArray[$idx]: $!"; 
              if (-e $destFileArray[$idx])
              {
                print "\n Copied $sourceFileArray[$idx] successfully to $destFileArray[$idx]";
              }
          }
          else
           {
                #remove as the file no longer needed in tmpdir
                print"\n Overwrite is not selected,hence skipped copying $sourceFileArray[$idx] to $destFileArray[$idx] as $destFileArray[$idx] exists";
                unlink($metadata[0]);
           }
        }
        else
        {
                 rename($metadata[0],$destFileArray[$idx]) or print "\nCan not move $metadata[0] to $destFileArray[$idx]: $!"; 
              if (-e $destFileArray[$idx])
              {
                print "\n Copied $sourceFileArray[$idx] successfully to $destFileArray[$idx]";
              }

        }
        

      }
      next;
   }
   if ($metadata[1] eq 'DIR')
   {
      #print "inside dir processing..$metadata[0]";
      if (-d $destFileArray[$idx])
      { 
       #ignore
      }
      else
      {
        print "Copying source directoy: $metadata[0] to destination file:$destFileArray[$idx] is skipped as it is not a valid operation";
        next; 
      }
       my $sdirnme = $metadata[0].$fileSep."*";
       my $ddirnme = $destFileArray[$idx];
       $targetdir = $ddirnme;
       $sourcedir = $metadata[0];
       cp_tree($metadata[0], \&create_dir);
       cp_files($metadata[0], $ddirnme);
      # my $cpopt   = "";
      #    if ($overWriteFlag eq "YES")
      #    { 
      #      $cpopt = $cpopt."-f ";
      #       if ($backupFlag eq "YES")
      #       {
      #         $cpopt = $cpopt."-b --suffix=.bak";
      #       }
      #     }
      #     else
      #     {
      #        $cpopt = "--reply=no ";
      #     }
#       `mv $sdirnme $ddirnme`;
      #   print "cp option:$cpopt";
      #  `cp -r $cpopt  $sdirnme $ddirnme`;
        rmtree($metadata[0],0,0);
        

       #remove the directory from destination as it is not required any more.
       #print "removing $metadata[0]";
       rmdir($metadata[0]);
            print "\n Copied $sourceFileArray[$idx] successfully to $targetdir";
            
   }
   
}
#clean up metadata file
unlink($metaFile);
rmdir($destDir.$fileSep.$tmpdirName);

exit 0;



sub cp_tree {
    my ($path, $code_ref) = @_;
    my ($DH, $file);
    if (-d $path) {
        $code_ref->($path);
        unless (opendir $DH, $path) {
            warn "Couldn't open $path.\n$!\nSkipping!";
            return;
        }
        while ($file = readdir $DH) {
            next if $file eq '.' || $file eq '..';
            cp_tree("$path/$file", $code_ref);
        }
    }
}

sub create_dir {
    my $copy = $_[0];
    substr($copy, 0, length($sourcedir), $targetdir);
    unless (-d $copy) {
        if (mkdir $copy) {
            #print "Created $copy\n";
        } else {
            print "Unable to create $copy.\n$!\n";
        }
    } else {
       # print "$copy already exists - skipping\n";
    }
}

sub cp_files {
use File::Copy;

    my ($path,$dest) = @_;
 #   print "inside cp_files $path,$dest";
    my ($DH, $file);
    if (-d $path) {
       
        unless (opendir $DH, $path) {
            warn "Couldn't open $path.\n$!\nSkipping!";
            return;
        }
        while ($file = readdir $DH) {
          # print $file;
            next if $file eq '.' || $file eq '..';
           if (-d "$path/$file")
            {
          #   print "recursive call";
             cp_files("$path/$file", "$dest/$file");
            }
           if (-f "$path/$file")
           {
            # print "Copying $path/$file as $dest/$file";
             my $dfile = "$dest/$file";

             if (-e $dfile)
             { 
             	if ($overWriteFlag eq "YES")
            	 { 
              	  if ($backupFlag eq "YES")
                  {
                    rename($dfile,"$dfile.bak");
                  }
                    copy("$path/$file",$dfile);
                 }
             } 
             else
             {
               copy("$path/$file",$dfile);
             }
           }
        }
    }
}


 
