#!/usr/local/bin/perl
# 
# $Header: wrap.pl 12-apr-2005.06:23:16 gsbhatia Exp $
#
# wrap.pl
# 
# Copyright (c) 2005, Oracle. All rights reserved.  
#
#    NAME
#      wrap.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)
#    gsbhatia    04/12/05 - gsbhatia_wrap_gc_plsql
#    gsbhatia    04/11/05 - Creation
# 
################################################################################

use lib "$ENV{'ADE_VIEW_ROOT'}/emcore/scripts/install";
use lib "$ENV{'ADE_VIEW_ROOT'}/emcore/sysman/admin/emdrep/bin";

use strict;
use Component;
use Repository;
use SQLFile;
use File::Basename;

my $AVR = $ENV{'ADE_VIEW_ROOT'};
die "not in view!!" if(!defined $AVR); 
my $WRAP=$ENV{'ORACLE_HOME'}.'/bin/wrap';
my $DIRSEP="/";

my $mode = shift ;
my $path = shift ;

if($mode eq '-root')
{
  if(-d $path)
  {
    my $repo = Repository->new();
    $repo->init($path);
    my @comps = $repo->getComponentsOrdered();
    foreach my $h (@comps)
    {
      wrapComponent($h);
    }    
    exit(0);
  }else
  {
    print "\ndirectory $path does not exists\n";
  }
}elsif($mode eq '-comp')
{
  if(-e $path)
  {
    my $comp = Component->new();
    if($comp->init($path))
    {
      wrapComponent($comp);
    }else
    {
      print "\nError parsing $path\n";
    }	    
    exit(0);
  }else
  {
    print "\nfile $path does not exists\n";
  }
}
printUsage();
exit(0);

sub wrapComponent
{
  my ($comp) = @_ ;

  print "parsing component ".$comp->getName()."\n";

  $comp->parse();

  my @list = $comp->getSQLFilesByTypes('pkgbodys');
  foreach my $sql (@list){
    my $sqlpath=$sql->getPath();
    my ($name, $path, $suffix)= fileparse($sqlpath, qr{\.sql});
    $path =~ s/(.*)\//$1/;
    my $command="$WRAP iname=$sqlpath oname=$path".$DIRSEP."$name";
    my $rc = 0xffff & system($command);
    die("could not execute $command: errorcode - ".$rc) unless $rc==0;
    my $plb = $path."$DIRSEP".$name.".plb";
    print $plb."\n";
    if (open(FIN, "$plb")){
      my @lines = <FIN>;
      close (FIN);
      if (open(FOUT, ">$plb")){
        print FOUT "Rem drv: ".$sql->{'header'}."\n";
        for my $line (@lines){
          print FOUT $line;
        }
        close (FOUT);
      }      
    }
  } 
}

sub printUsage
{
  print "

wrap.pl - wrap component pkg body sql scripts
Usage : perl \$ADE_VIEW_ROOT/emcore/sysman/admin/emdrep/bin/wrap.pl [ -root <dir> | -comp <file> ]
  <dir>  = absolute path of sql root directory
  <file> = absolute path of component.xml
  
";
}
