#!/usr/local/bin/perl
# 
# $Header: emdb/sysman/admin/scripts/readJarStream_v2.pl /st_emdbsa_11.2/1 2009/02/06 23:27:16 hasriniv Exp $
#
# readJarStream.pl
# 
# Copyright (c) 2007, 2009, Oracle and/or its affiliates.All rights reserved. 
#
#    NAME
#      readJarStream_v2.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)
#    hasriniv    12/05/08 - Creation
# 
use strict;
use File::Path;
my $jarCmd = shift(@ARGV);
my $metaFile = shift(@ARGV);
my $overWriteFlag = shift(@ARGV);
my $backupFlag = shift(@ARGV);
my $destTempDir = 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;



  chdir($destTempDir) or die "Can not find Destination Directory:$destTempDir";
  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: $! $?";



open(METAFILE, "< $metaFile" ) or die "Can't open $metaFile : $!";
my @metadataarray = ();
while(my $content = <METAFILE> )
{
   chomp($content);
   push(@metadataarray,$content);
}
close(METAFILE);
#process meta data in order
my $numofDestFiles = @metadataarray;

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

foreach my $fileInfo (@metadataarray)
{
  my @destFileInfo = split(";",$fileInfo);
  my $destFile     = $destFileInfo[1];
  if (-d $destFile)
  {;}
  else
  {
       $destFile = substr($destFile,0,rindex($destFile,$fileSep));
  }
  if (-d $destFile)
  {;}
  else
  {
    print "Error: Destination: $destFile does not exist"; 
    exit;
  }
  
}

for (my $idx=0;$idx <= $numofDestFiles-1; $idx++)
{

    my @metadata=split(";",$metadataarray[$idx]);

   if ($metadata[2] eq 'FIL')
   {
        my $vanillaFileName = $metadata[0];
        my $position = rindex($vanillaFileName,$fileSep)+1;
        my $dirName = substr($vanillaFileName,0,$position-1);
        my $vanillaFileName = substr($vanillaFileName,$position);
       if (-d $metadata[1])
       { 
         my $filNme = $metadata[1].$fileSep.$vanillaFileName;

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


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

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

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

        }
        

      }
      next;
   }
   if ($metadata[2] eq 'DIR')
   {
        my $vanillaFileName = $metadata[0];
        my $position = rindex($vanillaFileName,$fileSep)+1;
        my $dirName = substr($vanillaFileName,0,$position-1);
        my $vanillaFileName = substr($vanillaFileName,$position);
      #print "inside dir processing..$metadata[0]";
      if (-d $metadata[1])
      { 
       #ignore
      }
      else
      {
        print "Copying source directoy: $vanillaFileName to destination file:$metadata[1] is skipped as it is not a valid operation";
        next; 
      }
       my $sdirnme = $vanillaFileName.$fileSep."*";
       my $ddirnme = $metadata[1];
       $targetdir = $ddirnme;
       $sourcedir = $vanillaFileName;
       cp_tree($vanillaFileName, \&create_dir);
       cp_files($vanillaFileName, $ddirnme);
     
        rmtree($vanillaFileName,0,0);
      
       rmdir($vanillaFileName);
            print "\n Copied $metadata[0]successfully to $targetdir";
            
   }
   
}
#clean up metadata file
unlink($metaFile);
rmdir($destTempDir.$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);
             }
           }
        }
    }
}


