#################################################################################
#
# $Header: HeaderUtil.pm 14-jan-2005.10:55:47 ktlaw Exp $
#
# HeaderUtil.pm
#
# Copyright (c) 2003, 2005, Oracle. All rights reserved.  
#
#    NAME
#      HeaderUtil.pm - <one-line expansion of the name>
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#
#    MODIFIED   (MM/DD/YYYY)
#       ktlaw      01/14/05 - add comments 
#       ktlaw      01/13/05 - ktlaw_new_repmgr
#       ktlaw      01/10/05 - created
################################################################################
#!/usr/local/bin/perl
#
# HeaderUtil.pl - tools to mass insert RepManager Header
# Usage: $ADE_VIEW_ROOT/emcore/sysman/admin/emdrep/bin/HeaderUtil.pl  <path>
# <path> = absolute path of the directory containing sql files
#
# Notes:
# - HeaderUtil.pl search recursively under the specified directory. 
# - It must be run within a view with an open transaction
# - It does a best effort guessing only. You must verify the changes are correct. 
# - It does not resolve sequencing of sql files. If the sql files must be run in a specific 
#    sequence, you must manually edit the RepManager to achieve your desired effect.
# - It does not check in your changed files, you must run ade ci or ade ciall to check in the changes.
#


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

use SQLFile;
use Directory;

$AVN = $ENV{'ADE_VIEW_NAME'};
die "not in view!!" if(!defined $AVN);
$PWD = shift ;


sub insertHeader
{
  (my $file) = @_;
  my $sql = new SQLFile ;
  $sql->setPath($file);
  $sql->setType($sql->guessType);    
  if($sql->isValid)
  {
    my $ade = $sql->getPath;
    $ade =~ s/$PWD\///g ;
    print "executing ade co -c \"add repmgr header\" $ade\n";
    system "ade co -c \"add repmgr header\" $ade";
    if(open(FIN,$file))
    {
      my $type = $sql->getType;
      my $ver = $sql->getVersion;
      my @lines = <FIN> ;
      close(FIN);
      if(open(FOUT,">$file"))
      {
        if($type eq 'data_upgrade' || $type eq 'schema_upgrade')
        {
          print FOUT "Rem drv: <migrate type=\"$type\" version=\"$ver\"/> \n";
        }else
        {
          print FOUT "Rem drv: <create type=\"$type\"/> \n";
        }
        foreach $h (@lines)
        {
          print FOUT $h;
        }
        close(FOUT);
      }
    }
  }
}

my $d = new Directory;
$d->setPath($PWD);
$d->find(\&insertHeader,'true','\.sql');   
