#
# $Header: emrepmgr.pl 23-may-2008.16:46:59 chyu Exp $
#
# emrepmgr.pl
#
# Copyright (c) 2003, 2008, Oracle. All rights reserved.  
#
#    NAME
#      emrepmgr.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)
#     chyu       05/23/08 - removing the quiesce requirement via 6697464
#     chyu       09/13/07 - during the checking db objects, make sure there
#                           isn't 2 thread piping to file at the same time
#     vkhizder   08/07/07 - calling ecm metadata update only once during
#                           upgrade
#     sktedla    07/31/07 - sktedla_rfi_backport_4726892_10.2.0.4
#     chyu       07/23/07 - adding the error off/error on switch for parsing
#     chyu       07/16/07 - adding the _UPGRADE_ component logic for overall
#                           system progress
#     mfidanbo   04/04/07 - observe order
#     mfidanbo   03/01/07 - add test metadata execution
#     chyu       03/07/07 - backporting bug 5905191 - running dbms_jobs submit
#                           in em_repos_user credential only
#     gsbhatia   12/11/06 - Remove unnecessary ora error checks while listing
#                           upgrade errors
#     shianand   10/27/06 - fix bug 5482793
#     chyu       08/17/06 - making sysaux=sysaux_test
#     chyu       08/16/06 - adding the condition for filtering
#     chyu       07/18/06 - Backport chyu_bug-5305174 from 
#                           st_emcore_10.2.0.1.0 
#     kvsingh    07/20/06 - Bug 5360253 
#     chyu       07/10/06 - adding the connect string to the env instead of by 
#                           SQL define 
#     chyu       06/26/06 - adding the file directive for dbsa files 
#     chyu       05/17/06 - skipping sys credential during transx 
#     chyu       05/15/06 - create top level driver script for sa mode 
#     chyu       05/15/06 - skip transx in sysaux mode 
#     chyu       06/26/06 - adding the file directive for dbsa files 
#     chyu       05/17/06 - skipping sys credential during transx 
#     chyu       05/15/06 - create top level driver script for sa mode 
#     chyu       05/15/06 - skip transx in sysaux mode 
#     vesriniv   08/03/06 - add empa
#     chyu       04/28/06 - removing the limitation for transx execution 
#     chyu       04/07/06 - modifying the create_in_sysaux logic to use new 
#                           sets of headers 
#     jsadras    03/03/06 - grants on AUX_STATS to SYSMAN, Bug:5066208 
#     jsadras    03/07/06 - Backport jsadras_bug-5066208 from main 
#     gsbhatia   12/15/05 - Bug 4888848 
#     chyu       12/13/05 - skipping TransX in upgrade cases when CORE was not 
#                           modified 
#     chyu       12/13/05 - adding the out_of_box to the create during the 
#                           upgrade process 
#     chyu       11/11/05 - modifying the upgrade process to be more modular 
#     chyu       12/19/05 - XbranchMerge chyu_bug-4733827 from main 
#     asaraswa   09/07/05 - rolling back creation of CSA tablespace 
#     afontana   09/06/05 - add PATH_SEP 
#     chyu       08/30/05 - 
#     tthakur    08/17/05 - adding post_data_upgrade 
#     chyu       08/15/05 - removing the call of the admin_set_repos_version 
#                           script since the new repmanager would use the 
#                           components framework 
#     rdabbott   08/01/05 - fix 3941639: move emutil to oracle home 
#     asaraswa   07/26/05 - adding CSA tablespace
#     chyu       07/25/05 - switching the upgrade to the new rep manager 
#     chyu       07/25/05 - adding the pre_data_upgrade scripts to the upgrade 
#                           path 
#     chyu       07/25/05 - reverting the upgrade to the old upgrade process 
#                           until the new upgrade is debugged 
#     asaraswa   07/24/05 - adding CSA tablespace
#     ktlaw      07/22/05 - enable new repmgr 
#     ktlaw      07/20/05 - add upgradeEMSchemaNew 
#     ktlaw      07/19/05 - add new repmgr intg 
#     chyu       07/19/05 - adding the se to the core_init reference 
#     gsbhatia   07/04/05 - Adding comments 
#     chyu       06/22/05 - fixing bug 4439104-need addition session for 
#                           registering dbms jobs 
#     gsbhatia   06/15/05 - bug#4324801
#     gsbhatia   06/15/05 - revert bug#4028621 
#     ktlaw      06/10/05 - add empp 
#     gsbhatia   05/10/05 - bug#4028621 
#     asaraswa   05/04/05 - creating CSA tablespace 
#     ktlaw      04/26/05 - always use SYSMAN
#     bevoss     04/05/05 - Add hooks for emci SQL 
#     gsbhatia   03/18/05 - Load .dlf files into repository after upgrade 
#     gsbhatia   03/08/05 - bug 4178702 
#     afontana   03/02/05 - define more variables for upgrade 
#     afontana   03/01/05 - define oracle_home and connect_string in sqlplus 
#     ktlaw      02/22/05 - add -action dump 
#     ktlaw      02/17/05 - bug 4192609
#     ktlaw      01/04/05 - bug 4093478/4028621
#     ktlaw      01/17/05 - 
#     rpinnama   12/30/04 - Add pre/post import files 
#     rzazueta   12/10/04 - Pass EM_REPOS_USER to user_create_view_user.sql 
#     ktlaw      12/01/04 - fix code 41 
#     rpinnama   11/19/04 - Add the SQL*Plus variables available to all 
#                           scripts 
#     ktlaw      11/10/04 - update transx 
#     rzazueta   11/01/04 - Pass EM_REPOS_USER to sql files 
#     ktlaw      10/22/04 - use TransX.pm 
#     ktlaw      10/20/04 - add transx support 
#     rpinnama   09/24/04 - Use SYS to create db in SYSAUX 
#     lhan       09/14/04 - add CM support
#     rpinnama   08/25/04 - Add downgrade, reload, export and import actions 
#     ajdsouza   08/09/04 - Moved back component under core
#     ajdsouza   07/29/04 - Added storage component
#     rdabbott   07/07/04 - put links to repos sql in oh 
#     rdabbott   07/01/04 - print errors to stderr 
#     rdabbott   06/28/04 - core only create 
#     rpinnama   06/25/04 - Fetch EM version from MGMT_VERSIONS table 
#     rpinnama   05/03/04 - Dont use dbms_crypto functions in grid control. 
#     asawant    04/16/04 - Create jobs after OutOfBox - avoid partitioning 
#                           deadlocks.
#     rpinnama   04/15/04 - Support upgrade
#     gan        04/09/04 - bug 3562484 
#     mgoodric   12/15/03 - bug 3312919 
#     rzazueta   12/13/03 - Query db for temporary tablespace 
#     rpinnama   12/12/03 - Run emreposoutofbox for MAINSA repository creation 
#     mgoodric   12/10/03 - add missing MetaLink DEFINEs for create_in_sysaux
#     dsahrawa   12/01/03 - use core_funcs or core_funcs_10g depending on 
#                           database version 
#     mgoodric   11/18/03 - add support for MetaLink credentials
#     gan        11/14/03 - Avoid output passwd in log
#     gan        10/31/03 - prompt for user/passwd
#     rpatti     09/25/03 - remove exchange packages
#     rpinnama   07/26/03 - Dont check for init params during drop, and create_in_sysaux actions
#     rpinnama   07/25/03 - Use repos mode while creating user
#     skini      07/25/03 - Remove java processing
#     gmulchan   07/30/03 - adding ocs component
#     rpinnama   07/11/03 - Store repository mode also in versions table
#     rpinnama   07/10/03 - Fix month value in the formatted date
#     rpinnama   07/04/03 - Print in info mode
#     rpinnama   07/02/03 - Provide an option to write output to a file
#     rpinnama   07/01/03 - Modify parameters to emreposcre.sql
#     vnukal     04/17/03 - rep_schema on NT
#     rpinnama   03/31/03 - rpinnama_setup_repos_migration_main
#     rpinnama   03/28/03 - Use 5.6.1 strict
#     rpinnama   03/27/03 - Support creating local db
#     rpinnama   03/28/03 - Creation
################################################################################

require 5.6.1;
use strict;
use English;
use File::Temp qw/ tempfile tempdir /;
use DBI;
use TransX;
use Component;
use Repository;
use ScriptSession;
use IO::Handle;
use Logger;
use ExecJava;

## Constants.
my $EM_SQL_ERR_EXIT = "WHENEVER SQLERROR EXIT SQL.SQLCODE;";
my $EM_SQL_ERR_CONT = "WHENEVER SQLERROR CONTINUE;";
my $EM_CREATE_SEEDDB    = 1;
my $EM_CREATE_OUTOFBOX  = 1 << 1;
my $EM_CREATE_LOCALDB   = 1 << 2;
my $devNull = "/dev/null";
my $EM_PATH_SEP = ":";
if( ($OSNAME eq "MSWin32") or ($OSNAME eq "Windows_NT") )
{
    $devNull = "NUL";
    $EM_PATH_SEP = '"\;"';
}


my $progName = $0;
my $DRY_RUN = undef ;
my $ORACLE_HOME;
my $EMDW_HOME;
my $SQLPLUS;
my $EXPORT;
my $IMPORT;
my $LOADJAVA;
my $EM_SQL_SCRIPT_ROOT;
my $EM_LOADJAVA_JAR_ROOT;
my $EM_JOBTYPES_ROOT;
my $DBCONTROL_HEADER = 0;
my $DBCONTROL_SQLROOT;
my $NEED_SYS_CREDENTIAL = 1;
my $NEED_TEMP_TABLESPACE = 1;
my $OS_FLAG = 0;
my $NO_CONDITION = 0;

## Arguments..
# Connect String
my $EM_REPOS_CONNSTRING;

# Action requsted.
my $EM_REPOS_ACTION;

# Other arguments
my $EM_REPOS_USER;
my $EM_REPOS_PWD;
my $EM_REPOS_DBSYSPWD;
my $EM_DEFAULT_TABLESPACE;
my $EM_DEFAULT_DATAFILE_NAME;
my $EM_DEFAULT_DATAFILE_INIT_SIZE;
my $EM_DEFAULT_DATAFILE_EXTEND_SIZE;
my $EM_ECM_TABLESPACE;
my $EM_ECM_DATAFILE_NAME;
my $EM_ECM_DATAFILE_INIT_SIZE;
my $EM_ECM_DATAFILE_EXTEND_SIZE;
my $EM_ECM_CSA_TABLESPACE;
my $EM_ECM_CSA_DATAFILE_NAME;
my $EM_ECM_CSA_DATAFILE_INIT_SIZE;
my $EM_ECM_CSA_DATAFILE_EXTEND_SIZE;
my $EM_TEMP_TABLESPACE;
my $EM_CREATE_OPTIONS = 0;
my $EM_VERBOSE = 0;
my $EM_OUTPUT_FILENAME;
my $EM_ERROR_FILENAME;
my $EM_ECHO_SQL = "OFF";
my $METALINK_USERNAME;
my $METALINK_PASSWORD;
my $METALINK_URL;
my $EM_EXPORT_DIR;
my $EM_IMPORT_DIR;


# Derived values
# credentials..
my $EM_SYS_CREDENTIALS;
my $EM_REPOS_CREDENTIALS;
my $EM_REPOS_VERSION;

my $EM_FIRST_WRITE_TO_FILE = 1;
my $EM_REPOS_MODE = "CENTRAL";

######################################################################
# TRACE/LOG ROUTINES
######################################################################

sub write_to_file($) {
  my ($msg) = shift;

  my $file_to_open;

  chomp ($msg);
  if ($EM_FIRST_WRITE_TO_FILE > 0)
  {
      $file_to_open = "> " . $EM_OUTPUT_FILENAME;
      $EM_FIRST_WRITE_TO_FILE = 0;
  }
  else
  {
      $file_to_open = ">> " . $EM_OUTPUT_FILENAME;
  }

  if ( open(OUTPUT_FILE, $file_to_open) )
  {
     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
     if ($year<=1000) {$year += 1900;}
     $mon += 1;
     my $prefix = sprintf("%02d-%02d-%4d %02d:%02d:%02d",
                   $mday,$mon,$year,$hour,$min,$sec);

     printf(OUTPUT_FILE "[%s] %s\n",$prefix, $msg);
     close(OUTPUT_FILE);
  }
}

sub trace($) {
  my ($trcmsg) = shift;
  if ($EM_VERBOSE > 0)
  {
    write_to_file $trcmsg;
    print $trcmsg;
  }
}

sub traceln($) {
  my ($trcmsg) = shift;
  trace "$trcmsg\n";
}

sub info($) {
  my ($logmsg) = shift;
  write_to_file $logmsg;
  print $logmsg;
}

sub infoln($) {
  my ($logmsg) = shift;
  info "$logmsg\n";
}

######################################################################
# Main program.
######################################################################

$|=1; # Set AUTOFLUSH on

setEnviron();


ProcessCommandLine();

dumpEnviron();
dumpArguments();

# Check SYS credentials..
my $rc = checkSYSCredentials();
if ($rc ne 0)
{
  info "SYS credentials or connect string is invalid.\n";
  exit 3;
}

if ($EM_REPOS_ACTION eq "create")
{
    # Check if DB satisfies init criteria.
    $rc = checkDBInitParams();
    if ($rc ne 0)
    {
      info "Database does not satisfy init parameter criteria.\n";
      exit 10;
    }

    # Remote database..
    if(!defined $DRY_RUN || $DRY_RUN ne 'true')
    {
    if ($EM_CREATE_OPTIONS & $EM_CREATE_SEEDDB)
    {
      # Check for repository User..
      my $reposUserExists = 0;
      $reposUserExists = checkReposUser();
      if ($reposUserExists eq 0)
      {
        info "Repository Creation failed. Repos User already exists..\n";
        exit 11;
      }

      # Setup DB.
      loadNecessaryObjects();

      # Create user
      $rc = createReposUser();
      if ($rc ne 0)
      {
        info "Repository Creation failed. Failed to create Repos User.\n";
        exit 12;
      }
    }
    elsif ($EM_CREATE_OPTIONS & $EM_CREATE_OUTOFBOX)
    {
      # We reach here if seed db create option is not selected
      # and out of box setup is selected.
      # So check if repos user exists..
      my $reposUserExists = 0;
      $reposUserExists = checkReposUser();
      if ($reposUserExists ne 0)
      {
        info "Repository Out of box setup failed. Repos User does not exist..\n";
        exit 13;
      }
    }
    }
    
    $rc = createEMSchemaNew();
    
    if ($rc ne 0)
    {
      info "Repository Creation failed. Failed to create repository schema.\n";
      exit 14;
    }

  # Check if the repository is created successfully..
  $rc = checkForErrors();
  if ($rc ne 0)
  {
      info "Repository Creation has errors. Please check file $EM_OUTPUT_FILENAME for detailed errors.\n";
      exit 15;
  }

  info "Repository Creation Successful.\n";
}
elsif ($EM_REPOS_ACTION eq "create_in_sysaux_test")
{
  if ( $DBCONTROL_HEADER != 1)
  {
    $rc = createEMSchemaInLocalDB();
    if ($rc == 0)
    {
       $rc = checkForErrors();
      if ($rc ne 0)
      {
         info "Repository Creation has errors. Please check file $EM_OUTPUT_FILENAME for detailed errors.\n";
         exit 15;
      }
      info "Repository Creation Successful.\n";
    }
    else
    {
      info "Repository Creation Has Error with Exit Code:$rc\n";
    }
    exit $rc;
  }
}
elsif ($EM_REPOS_ACTION eq "create_in_sysaux")
{
  # Check for repository User..
  my $reposUserExists = 0;
  $reposUserExists = checkReposUser();
  if ($reposUserExists eq 0)
  {
    info "Repository Creation failed. Repos User already exists..\n";
    exit 20;
  }
  # Setup DB.
  loadNecessaryObjects();

  # Create user
  $rc = createReposUser();
  if ($rc ne 0)
  {
    info "Repository Creation failed. Failed to create Repos User.\n";
    exit 12;
  }

  # Create user loadjars and schema in local database.
  # $rc = createEMSchemaInLocalDB();
  
  # Using the new create mechanism
  $rc = createEMSchemaNew();
  
  if ($rc ne 0)
  {
    info "Repository Creation for local database failed.\n";
    exit 21;
  }

  $rc = checkForErrors();
  if ($rc ne 0)
  {
      info "Repository Creation for local database has errors. Please check file $EM_OUTPUT_FILENAME for detailed errors.\n";
      exit 22;
  }

  info "Repository Creation Successful.\n";
}
elsif ($EM_REPOS_ACTION eq "drop")
{
  info "Dropping the repository..\n";

  # Quise the db
  # commenting out the quiesce requirement via 6697464
  # quiesceDB();

  # Check if repos user exists..
  my $reposUserExists = 1;
  $reposUserExists = checkReposUser();
  if ($reposUserExists eq 0)
  {
    info "Repos User exists..\n";

    # Clear EM Contexts
    clearContexts();

    # Drop EM users (other than repos user)
    dropEMUsers();

    # Drop Repos user
    dropReposUser();
  }
  else
  {
    info "Repos User does not exist ...  Continuing with cleanup ...\n";
  }

  # Drop Roles/Synonyms
  dropRoles();

  # Unquiesce the DB
  # commeting out the quiesce requirement via 6697464
  # unquieseDB();

  # Check if the repository is dropped successfully..
  $rc = checkForErrors();
  if ($rc ne 0)
  {
      info "Dropping Repository failed. Please check file $EM_OUTPUT_FILENAME for detailed errors.\n";
      exit 30;
  }
  info "Dropped Repository Successfully.\n";
}
elsif ($EM_REPOS_ACTION eq "upgrade")
{
  # Check if DB satisfies init criteria.
  # Is this required?
  #$rc = checkDBInitParams();
  #if ($rc ne 0)
  #{
  #  info "Database does not satisfy init parameter criteria.\n";
  #  exit 40;
  #}
  info "Upgrading the repository..\n";

  # Check for repository User..
  my $reposUserExists = 0;
  $reposUserExists = checkReposUser();
  if ($reposUserExists ne 0)
  {
    info "Repos User does not exist..\n";
    exit 41;
  }

  ### Check if the repository is in the right version to be upgraded.
  #info "Checking repository version and mode\n";
  #$EM_REPOS_VERSION = getReposVersion();
  #if ( $EM_REPOS_VERSION eq "10.2.0.0.0")
  #{
  #  info "Repository Upgrade cannot be performed. \n";
  #  info "Repository is already upgraded to 10.2.0.0.0 \n";
  #  exit 43;
  #}


  # Setup DB
  loadNecessaryObjects();

  ### Check if the repository is in the right version to be upgraded.
  info "Checking repository version..\n";

  setSchemaStatus('_UPGRADE_',2);
  # Perform Schema and data Upgrade
  $rc = upgradeEMSchemaNew();
  if ($rc ne 0)
  {
    setSchemaStatus('_UPGRADE_',3);
    info "Repository Upgrade failed. Failed to upgrade repository schema.\n";
    exit 42;
  }

  $rc = listUpgradeErrors();
  if ($rc ne 0)
  {
    setSchemaStatus('_UPGRADE_',3);
    info "Repository Upgrade has errors. Please check file $EM_OUTPUT_FILENAME for detailed errors.\n";
    exit 45;
  }
  else
  {
    setSchemaStatus('_UPGRADE_',4);
  }
  info "Repository Upgrade Successful.\n";

}
elsif ($EM_REPOS_ACTION eq "downgrade")
{
  info "Downgrading the repository..\n";

  # Check for repository User..
  my $reposUserExists = 0;
  $reposUserExists = checkReposUser();
  if ($reposUserExists ne 0)
  {
    info "Repos User does not exist..\n";
    exit 41;
  }

  # Perform data & Schema downgrade
  $rc = downgradeEMSchema();
  if ($rc ne 0)
  {
    info "Repository Downgrade failed. Failed to downgrade repository schema.\n";
    exit 42;
  }

  #$rc = listDowngradeErrors();
  #if ($rc ne 0)
  #{
  #  info "Repository Downgrade has errors. Please check file $EM_OUTPUT_FILENAME for detailed errors.\n";
  #  exit 45;
  #}
  info "Repository Downgrade Successful.\n";
}
elsif ($EM_REPOS_ACTION eq "reload")
{
  info "Reloading the EM repository..\n";

  # Check for repository User..
  my $reposUserExists = 0;
  $reposUserExists = checkReposUser();
  if ($reposUserExists ne 0)
  {
    info "Repos User does not exist..\n";
    exit 41;
  }

  $rc = reloadEMSchema();
  if ($rc ne 0)
  {
    info "Repository reload failed. Failed to reload repository schema.\n";
    exit 42;
  }

  #$rc = listReloadErrors();
  #if ($rc ne 0)
  #{
  #  info "Repository reload has errors. Please check file $EM_OUTPUT_FILENAME for detailed errors.\n";
  #  exit 45;
  #}
  info "Repository reload Successful.\n";
}
elsif ($EM_REPOS_ACTION eq "export")
{
  # Not fully implemented.
  info "Exporting the EM repository..\n";

  # Check for repository User..
  my $reposUserExists = 0;
  $reposUserExists = checkReposUser();
  if ($reposUserExists ne 0)
  {
    info "Repos User does not exist..\n";
    exit 51;
  }

  $rc = exportEMRepository();
  if ($rc ne 0)
  {
    info "Repository Export failed.\n";
    exit 52;
  }

  #$rc = listEMUsers();
  #if ($rc ne 0)
  #{
  #  info "Repository Export failed. Failed to list EM users.\n";
  #  exit 53;
  #}

  info "Repository Export Successful.\n";
}
elsif ($EM_REPOS_ACTION eq "import")
{
  # Not fully implemented.
  info "Importing the EM repository..\n";

  # Check if DB satisfies init criteria.
  $rc = checkDBInitParams();
  if ($rc ne 0)
  {
    info "Database does not satisfy init parameter criteria.\n";
    exit 60;
  }

  # Check for repository User..
  my $reposUserExists = 0;
  $reposUserExists = checkReposUser();
  if ($reposUserExists eq 0)
  {
    info "Repository Import failed. Repos User already exists..\n";
    exit 61;
  }

  # Setup DB.
  loadNecessaryObjects();

  # Create user
  $rc = createReposUser();
  if ($rc ne 0)
  {
    info "Repository Import failed. Failed to create Repos User.\n";
    exit 62;
  }

  # Pre - import actions
  $rc = preImportActions();
  if ($rc ne 0)
  {
    info "Repository Import failed. Failed to perform pre import actions\n";
    exit 52;
  }

  # Import data
  $rc = importEMRepository();
  if ($rc ne 0)
  {
    info "Repository Import failed.\n";
    exit 52;
  }

  # Recompile packages
  # Create a public MGMT_USER role
  # Create MGMT_VIEW user and grant select on mgmt$ views
  # Create EM users
  # Enable VPD policy
  # Start DBMS jobs
  # Reset the sequences
  $rc = postImportActions();
  if ($rc ne 0)
  {
    info "Repository Import failed. Performing post import actions\n";
    exit 52;
  }

  info "Repository Import Successful.\n";
}
elsif($EM_REPOS_ACTION eq 'transx')
{
  info "Uploading DLF files to repository..\n";

  # Validate for repository User..
  my $reposUserExists = 0;
  $reposUserExists = validateReposUser();
  if ($reposUserExists ne 0)
  {
    info "Repos User does not exist..\n";
    exit 41;
  }
   &execTransX;
}
elsif($EM_REPOS_ACTION eq 'version')
{
  my $version = getReposVersion();
  print "\n\n Repository version = $version \n\n" ;
}
elsif($EM_REPOS_ACTION eq 'dump')
{
  dumpRepository();
}
else
{
  displayHelp();
  exit 99;
}
#################### END of MAIN #####################################

sub execTransX
{
    my $tx = new TransX;
    $tx->run("$ORACLE_HOME/sysman/admin/emdrep/rsc",$EM_REPOS_CONNSTRING,
            $EM_REPOS_USER, $EM_REPOS_PWD, $EM_OUTPUT_FILENAME, $EM_VERBOSE);
}

sub parseMetadataFile
{
  (my $File) = @_;
  print "Found Metadata File: $File\n";
  #parse the file
  my $defFile = undef;
  my $line = undef;
  my $javaWrapper = new ExecJava;
  
  open($defFile, $File);
  while ($line = <$defFile>)
  {
    chomp($line);
    if($line =~ '^\$ORACLE_HOME')
    {
      $line =~ s/\$ORACLE_HOME/$ORACLE_HOME/g;
      print "Adding $line\n";
      $javaWrapper->addClasspath($line);
    }
    else
    {
      print "Running $line\n";
      $javaWrapper->run($line, $EM_REPOS_CONNSTRING, $EM_REPOS_USER, $EM_REPOS_PWD, $EM_OUTPUT_FILENAME, "");
    }
  }
  close($defFile);
}

sub execMetadata
{
  &parseMetadataFile("$ORACLE_HOME/sysman/admin/emdrep/sql/core/latest/test_metadata/core.def");
  my $dirScanner = new Directory();
  $dirScanner->setPath("$ORACLE_HOME/sysman/admin/emdrep/sql");
  $dirScanner->find(\&parseMetadataFile, 'true', '^test_metadata[\w]*\.def$');
}

#
# set the following environment variables..
sub setEnviron()
{
  if ($ENV{ORACLE_HOME} eq "" )
  {
    info "Please specify ENV variable ORACLE_HOME \n";
    exit 2;
  }

  #Convert NT path to *ix path in OH string
  $ENV{ORACLE_HOME} =~ s#\\#/#g;
  $ENV{EMDW_HOME} =~ s#\\#/#g;
  $ORACLE_HOME = $ENV{ORACLE_HOME};
  $EMDW_HOME = "$ORACLE_HOME";

  $SQLPLUS = $ENV{SQLPLUS};
  if ( $SQLPLUS eq "" )
  {
    $SQLPLUS = "$ORACLE_HOME/bin/sqlplus ";
  }

  $EM_SQL_SCRIPT_ROOT = $ENV{EM_SQL_SCRIPT_ROOT};
  if ($EM_SQL_SCRIPT_ROOT eq "")
  {
    $EM_SQL_SCRIPT_ROOT="$EMDW_HOME/sysman/admin/emdrep/sql";
  }

  $EXPORT = $ENV{EXPORT};
  if ( $EXPORT eq "" )
  {
    $EXPORT = "$ORACLE_HOME/bin/exp ";
  }

  $IMPORT = $ENV{IMPORT};
  if ( $IMPORT eq "" )
  {
    $IMPORT = "$ORACLE_HOME/bin/imp ";
  }

  $LOADJAVA=$ENV{LOADJAVA};
  if ( $LOADJAVA eq "" )
  {
    $LOADJAVA = "$ORACLE_HOME/bin/loadjava";
  }

  $EM_LOADJAVA_JAR_ROOT = $ENV{EM_LOADJAVA_JAR_ROOT};
  if ( $EM_LOADJAVA_JAR_ROOT eq "" )
  {
    $EM_LOADJAVA_JAR_ROOT = "$EMDW_HOME/sysman/admin/emdrep/lib";
  }

  $EM_JOBTYPES_ROOT=$ENV{EM_JOBTYPES_ROOT};
  if ( $EM_JOBTYPES_ROOT eq "" )
  {
    $EM_JOBTYPES_ROOT = "$EMDW_HOME/sysman/admin/emdrep/bin";
  }

}

# Dump the environment being used.
sub dumpEnviron()
{
    # Reset output file..

    trace "Environment : \n";
    trace "ORACLE HOME          = $ORACLE_HOME \n";
    trace "REPOSITORY HOME      = $EMDW_HOME \n";
    trace "SQLPLUS              = $SQLPLUS \n";
    trace "SQL SCRIPT ROOT      = $EM_SQL_SCRIPT_ROOT \n";
    trace "EXPORT               = $EXPORT \n";
    trace "IMPORT               = $IMPORT \n";
    trace "LOADJAVA             = $LOADJAVA \n";
    trace "JAR FILE ROOT        = $EM_LOADJAVA_JAR_ROOT \n";
    trace "JOB TYPES ROOT       = $EM_JOBTYPES_ROOT \n";
}

# Create a temporary file
# create_temp_file()
# return fileHandle and fileName
sub create_temp_file(;$)
{
  my ($suffix) = @_;
  my $dir = tempdir(CLEANUP => 1);
  my $temp_fh;
  my $temp_filename;

  if(defined($suffix))
  {
     ($temp_fh, $temp_filename) = tempfile(DIR => $dir, SUFFIX => $suffix);
  }
  else
  {
    ($temp_fh, $temp_filename) = tempfile(DIR => $dir);
  }

  return ($temp_fh, $temp_filename);
}

#
# Display help
sub displayHelp()
{
  print STDERR <<EOM;
Usage: $progName <repos_details> [ options ]
 where
  <repos_details> := ([<repHost> <repPort> <repSID>] | [-connect \"<connectDescriptor>\"])
    <repHost>  -- host name to be used for the repository
    <repPort>  -- port number to be used for the repository
    <repSID>   -- SID to use for the repository
    <connectDescriptor> -- the connect descriptor of the repository
       For eg. :
         (DESCRIPTION=
          (ADDRESS_LIST=
           (ADDRESS=(PROTOCOL=TCP)(HOST=host1)(PORT=1521))
           (ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=1522)))
          (CONNECT_DATA=(SERVICE_NAME=servicename)))
       The connect string must be within double quotes.
       To determine the servicename connect as sys then:
       SQL>select value from v\$parameter where name='service_names'
  options :
   -action <actioncode> -
     where <actioncode> is one of the following :
     create  - to create EM repository
     create_in_sysaux - to create EM repository in SYSAUX
                  SYSAUX creation is not supported for remote databases.
     drop    - to drop existing EM repository
     upgrade - to upgrade existing EM repository
     transx  - to upload  DLF files to EM repository
     dump    - to dump info about tables, types and indices
     Default action is create
   -sys_password <password> - password of SYS database user
   -seed_db  - Creates only the seed repository
             - Valid only with create action
   -out_of_box_setup - Performs out of box setup
                     - Valid only with create action
   -repos_user <repUser> - repository schema user
                           Defaults to SYSMAN
   -repos_password <repPassword> - repository schema password
                           Defaults to SYSMAN
			   (not required in case of drop action)
   -verbose - generates verbose output
   -output_file <out file name>
      Specifies the name of the file where the output is written to
   -repos_tblspace <default tablespace name> -
      Specifies the default tablespace name
      Defaults to MGMT_TABLESPACE
   -datafile <management tablespace filename> -
      Specifies the full path name for the default tablespace file.
      Defaults to \$ORACLE_HOME/dbs/mgmt.dbf
   -ecm_tblspace <ecm depot tablespace name> -
      Specifies the ECM depot tablespace name
      Defaults to MGMT_ECM_DEPOT_TS
   -ecm_datafile <ecm depot tablespace filename> -
      Specifies the full path name for the ECM depot tablespace file.
      Defaults to \$ORACLE_HOME/dbs/mgmt_ecm_depot1.dbf
   -ecm_csa_tblspace <ecm csa tablespace name> -
      Speficies the ECM CSA tablespace name
      Defaults to MGMT_ECM_CSA_TS
   -ecm_csa_datafile <ecm csa tablespace filename> -
      Specifies the full path name for the EM CSA tablespace file.
      Defaults to \$ORACLE_HOME/dbs/mgmt_ecm_csa1.dbf
   -metalink_username <metalinkUsername> - MetaLink user name
      Defaults to _NOT_AVAILABLE_
   -metalink_password <metalinkPassword> - MetaLink user password
      Defaults to _NOT_AVAILABLE_
   -metalink_url <metalinkURL> - MetaLink HTTP URL
      Defaults to http://updates.oracle.com

EOM
}

######################################################################
# prompt for user/passwd input
# parament: prompt string, 0/1 for hide/show echo
# return: user input
######################################################################
sub PromptUserPasswd($$)
{
   my ($prompt, $echo) = @_;
   my $userinput;
   info $prompt;
   if ($echo eq 0 )
   {
      system "stty -echo"; # Non portable until ReadKey is picked up ...
      $userinput=<STDIN>;
      system "stty echo";  # Non portable until ReadKey is picked up ...
                           # Once ReadKey is picked up use the following.
                           # ReadMode('noecho');
                           # $userinput = ReadLine(0);
                           # ReadMode('normal');
      info "\n";
    }
    else
    {
      $userinput=<STDIN>;
    }
   chomp ($userinput);
   return $userinput;
}
######################################################################
# ProcessCommandLine : Processes command line parameters.
######################################################################
sub ProcessCommandLine()
{
  my @args = @ARGV;
  my $connString = "";
  my ($repHost, $repPort, $repSid);

  my $argCount = scalar(@args);
 

  if ($argCount lt 1)
  {
    displayHelp();
    exit 1;
  }

  if ($args[0] eq "-connect")
  {
    shift( @args );
    $connString = $args[0];
    shift( @args );
  }
  else
  {
    $repHost = $args[0];
    $repPort = $args[1];
    $repSid  = $args[2];
    shift( @args );
    shift( @args );
    shift( @args );
    $connString = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=$repHost)(Port=$repPort))(CONNECT_DATA=(SID=$repSid)))"
  }

  $EM_REPOS_CONNSTRING = $connString;

  $ENV{EM_REPOS_CONNECT_STRING} = $EM_REPOS_CONNSTRING;

  # Process rest of the arguments..
  while (scalar(@args) gt 0)
  {
    if ($args[0] eq "-action")
    {
      shift( @args );
      $EM_REPOS_ACTION = $args[0];
      shift( @args );
    }
    elsif ($args[0] eq "-sys_password")
    {
      shift( @args );
      $EM_REPOS_DBSYSPWD = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-repos_user")
    {
      shift( @args );
      $EM_REPOS_USER = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-repos_password")
    {
      shift( @args );
      $EM_REPOS_PWD = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-repos_tblspace")
    {
      shift( @args );
      $EM_DEFAULT_TABLESPACE = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-datafile")
    {
      shift( @args );
      $EM_DEFAULT_DATAFILE_NAME = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-ecm_tblspace")
    {
      shift( @args );
      $EM_ECM_TABLESPACE = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-dry_run")
    {
      shift( @args );
      $DRY_RUN = 'true';
    }
    elsif($args[0] eq "-ecm_datafile")
    {
	shift(@args);
        $EM_ECM_DATAFILE_NAME = $args[0];
        shift(@args);
    }
    elsif($args[0] eq "-ecm_csa_tblspace")
    {
      shift( @args );
      $EM_ECM_CSA_TABLESPACE = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-ecm_csa_datafile")
    {
      shift( @args );
      $EM_ECM_CSA_DATAFILE_NAME = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-seed_db")
    {
      shift( @args );
      $EM_CREATE_OPTIONS |= $EM_CREATE_SEEDDB;
    }
    elsif($args[0] eq "-out_of_box_setup")
    {
      shift( @args );
      $EM_CREATE_OPTIONS |= $EM_CREATE_OUTOFBOX;
    }
    elsif($args[0] eq "-verbose")
    {
      shift( @args );
      $EM_VERBOSE = 1;
    }
    elsif($args[0] eq "-output_file")
    {
      shift( @args );
      $EM_OUTPUT_FILENAME = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-metalink_username")
    {
      shift( @args );
      $METALINK_USERNAME = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-metalink_password")
    {
      shift( @args );
      $METALINK_PASSWORD = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-metalink_url")
    {
      shift( @args );
      $METALINK_URL = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-export_dir")
    {
      shift( @args );
      $EM_EXPORT_DIR = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-import_dir")
    {
      shift( @args );
      $EM_IMPORT_DIR = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-dbcontrol_header")
    {
      shift( @args );
      $DBCONTROL_HEADER = 1;
      $DBCONTROL_SQLROOT = $args[0];
      shift( @args );
    }
    elsif($args[0] eq "-no_condition")
    {
      shift( @args );
      $NO_CONDITION = 1;
    }
    else
    {
      displayHelp();
      exit 1;
    }
  }

  # Default the action to create.
  if ($EM_REPOS_ACTION eq "")
  {
    $EM_REPOS_ACTION = "create";
  }

  if ($EM_REPOS_ACTION eq "create_in_sysaux")
  {
      $EM_REPOS_MODE = "SYSAUX";
      $EM_CREATE_OPTIONS |= $EM_CREATE_LOCALDB;
      # we want out of box things as well in SYSAUX mode
      $EM_CREATE_OPTIONS |= $EM_CREATE_OUTOFBOX;
      $EM_REPOS_ACTION = "create_in_sysaux_test";
  }

  if ($EM_REPOS_ACTION eq "transx")
  {
  	$NEED_SYS_CREDENTIAL = 0;
  	$NEED_TEMP_TABLESPACE = 0;
  }
  
  if ($DBCONTROL_HEADER != 1)
  {
      if ($NEED_SYS_CREDENTIAL == 1) {
      # Override env default if any..
		  if ($EM_REPOS_DBSYSPWD eq "")
		  {
			  $EM_REPOS_DBSYSPWD = $ENV{EM_REPOS_DBSYSPWD};
			  
              if ($EM_REPOS_DBSYSPWD eq "")
              {
			  	$EM_REPOS_DBSYSPWD = &PromptUserPasswd("Enter SYS user's password : ", 0);

			  	if ($EM_REPOS_DBSYSPWD eq "")
			  	{
					  my $rc = checkOSAuthentication();
					  if ($rc eq 0)
					  {
						   $OS_FLAG = 1;
						   info "user os authenticated\n";
	
					  }
					  else
					  {
						  $OS_FLAG = 0;
					  }
			  	}
			 }
		  }
      }
  }

  if ($EM_REPOS_USER eq "")
  {
    $EM_REPOS_USER = $ENV{EM_REPOS_USER};
    if ($EM_REPOS_USER eq "")
    {
      $EM_REPOS_USER = &PromptUserPasswd("Enter repository user name : ", 1);
      #if ($EM_REPOS_USER eq "")
      #{
          $EM_REPOS_USER = "SYSMAN";
      #}
    }
  }
  $EM_REPOS_USER = uc $EM_REPOS_USER;
  if ($EM_REPOS_PWD eq "")
  {
    $EM_REPOS_PWD = $ENV{EM_REPOS_PWD};
    if ($EM_REPOS_PWD eq "")
    {
      if ($EM_REPOS_ACTION ne 'drop'){
        $EM_REPOS_PWD = &PromptUserPasswd("Enter repository user password : ", 0);
      }
      if ($EM_REPOS_PWD eq "")
      {
          $EM_REPOS_PWD = "SYSMAN";
      }
    }
  }
  if (!defined $METALINK_USERNAME || $METALINK_USERNAME eq "")
  {
    $METALINK_USERNAME = $ENV{'METALINK_USERNAME'};
    if (!defined $METALINK_USERNAME || $METALINK_USERNAME eq "")
    {
      if ($EM_REPOS_ACTION eq "create")
      {
        $METALINK_USERNAME=&PromptUserPasswd("Enter MetaLink user name : ", 1);
      }
      if (!defined $METALINK_USERNAME || $METALINK_USERNAME eq "")
      {
        $METALINK_USERNAME = "_NOT_AVAILABLE_";
      }
    }
  }
  if (!defined $METALINK_PASSWORD || $METALINK_PASSWORD eq "")
  {
    $METALINK_PASSWORD = $ENV{'METALINK_PASSWORD'};
    if (!defined $METALINK_PASSWORD || $METALINK_PASSWORD eq "")
    {
      if ($EM_REPOS_ACTION eq "create")
      {
        $METALINK_PASSWORD=&PromptUserPasswd("Enter MetaLink user password : ", 0);
      }
      if (!defined $METALINK_PASSWORD || $METALINK_PASSWORD eq "")
      {
        $METALINK_PASSWORD = "_NOT_AVAILABLE_";
      }
    }
  }
  if (!defined $METALINK_URL || $METALINK_URL eq "")
  {
    $METALINK_URL = $ENV{'METALINK_URL'};
    if (!defined $METALINK_URL || $METALINK_URL eq "")
    {
      $METALINK_URL = "http://updates.oracle.com";
    }
  }
  if ($EM_DEFAULT_TABLESPACE eq "")
  {
    $EM_DEFAULT_TABLESPACE = $ENV{EM_DEFAULT_TABLESPACE};
    if ($EM_DEFAULT_TABLESPACE eq "")
    {
      if ($EM_CREATE_OPTIONS & $EM_CREATE_LOCALDB)
      {
        $EM_DEFAULT_TABLESPACE = "SYSAUX";
      }
      else
      {
        $EM_DEFAULT_TABLESPACE = "MGMT_TABLESPACE";
      }
    }
  }
  if ($EM_DEFAULT_DATAFILE_NAME eq "")
  {
    $EM_DEFAULT_DATAFILE_NAME = $ENV{EM_DEFAULT_DATAFILE_NAME};
    if ($EM_DEFAULT_DATAFILE_NAME eq "")  { $EM_DEFAULT_DATAFILE_NAME = "mgmt.dbf"; }
  }
  if ($EM_DEFAULT_DATAFILE_INIT_SIZE eq "")
  {
    $EM_DEFAULT_DATAFILE_INIT_SIZE = $ENV{EM_DEFAULT_DATAFILE_INIT_SIZE};
    if ($EM_DEFAULT_DATAFILE_INIT_SIZE eq "")  { $EM_DEFAULT_DATAFILE_INIT_SIZE = "20m"; }
  }
  if ($EM_DEFAULT_DATAFILE_EXTEND_SIZE eq "")
  {
    $EM_DEFAULT_DATAFILE_EXTEND_SIZE = $ENV{EM_DEFAULT_DATAFILE_EXTEND_SIZE};
    if ($EM_DEFAULT_DATAFILE_EXTEND_SIZE eq "")
    { $EM_DEFAULT_DATAFILE_EXTEND_SIZE = "20m"; }
  }
  if ($EM_ECM_TABLESPACE eq "")
  {
    $EM_ECM_TABLESPACE = $ENV{EM_ECM_TABLESPACE};
    if ($EM_ECM_TABLESPACE eq "")
    {
      if ($EM_CREATE_OPTIONS & $EM_CREATE_LOCALDB)
      {
        $EM_ECM_TABLESPACE = "SYSAUX";
      }
      else
      {
        $EM_ECM_TABLESPACE = "MGMT_ECM_DEPOT_TS";
      }
    }
  }
  if ($EM_ECM_DATAFILE_NAME eq "")
  {
    $EM_ECM_DATAFILE_NAME = $ENV{EM_ECM_DATAFILE_NAME};
    if ($EM_ECM_DATAFILE_NAME eq "")  { $EM_ECM_DATAFILE_NAME = "mgmt_ecm_depot1.dbf"; }
  }
  if ($EM_ECM_DATAFILE_INIT_SIZE eq "")
  {
    $EM_ECM_DATAFILE_INIT_SIZE = $ENV{EM_ECM_DATAFILE_INIT_SIZE};
    if ($EM_ECM_DATAFILE_INIT_SIZE eq "")  { $EM_ECM_DATAFILE_INIT_SIZE = "100m"; }
  }
  if ($EM_ECM_DATAFILE_EXTEND_SIZE eq "")
  {
    $EM_ECM_DATAFILE_EXTEND_SIZE = $ENV{EM_ECM_DATAFILE_EXTEND_SIZE};
    if ($EM_ECM_DATAFILE_EXTEND_SIZE eq "")  { $EM_ECM_DATAFILE_EXTEND_SIZE = "100m"; }
  }
#CSA tablespace
  if ($EM_ECM_CSA_TABLESPACE eq "")
  {
    $EM_ECM_CSA_TABLESPACE = $ENV{EM_ECM_CSA_TABLESPACE};
    if ($EM_ECM_CSA_TABLESPACE eq "")
    {
      if ($EM_CREATE_OPTIONS & $EM_CREATE_LOCALDB)
      {
        $EM_ECM_CSA_TABLESPACE = "SYSAUX";
      }
      else
      {
        $EM_ECM_CSA_TABLESPACE = "MGMT_TABLESPACE";
      }
    }
  }
  if ($EM_ECM_CSA_DATAFILE_NAME eq "")
  {
    $EM_ECM_CSA_DATAFILE_NAME = $ENV{EM_ECM_CSA_DATAFILE_NAME};
    if ($EM_ECM_CSA_DATAFILE_NAME eq "")  { $EM_ECM_CSA_DATAFILE_NAME = "mgmt_ecm_csa1.dbf"; }
  }
  if ($EM_ECM_CSA_DATAFILE_INIT_SIZE eq "")
  {
    $EM_ECM_CSA_DATAFILE_INIT_SIZE = $ENV{EM_ECM_CSA_DATAFILE_INIT_SIZE};
    if ($EM_ECM_CSA_DATAFILE_INIT_SIZE eq "")  { $EM_ECM_CSA_DATAFILE_INIT_SIZE = "100m"; }
  }
  if ($EM_ECM_CSA_DATAFILE_EXTEND_SIZE eq "")
  {
    $EM_ECM_CSA_DATAFILE_EXTEND_SIZE = $ENV{EM_ECM_CSA_DATAFILE_EXTEND_SIZE};
    if ($EM_ECM_CSA_DATAFILE_EXTEND_SIZE eq "")  { $EM_ECM_CSA_DATAFILE_EXTEND_SIZE = "100m"; }
  }

  if ($EM_TEMP_TABLESPACE eq "")
  {
	if ($NEED_TEMP_TABLESPACE == 1) {
        $EM_TEMP_TABLESPACE = $ENV{EM_TEMP_TABLESPACE};
        if ($EM_TEMP_TABLESPACE eq "")  
        { 
            $EM_TEMP_TABLESPACE = getTempTablespace(); 
        }
        else 
        { 
            validateTempTablespace($EM_TEMP_TABLESPACE); 
        }
	}
  }
  
  # If no create option (local_db, seed_db, out_of_box_setup) is specified
  # perform both (seed_db and out_of_box_setup)
  if ($EM_CREATE_OPTIONS eq 0)
  {
    $EM_CREATE_OPTIONS |= $EM_CREATE_SEEDDB;
    $EM_CREATE_OPTIONS |= $EM_CREATE_OUTOFBOX;
  }

  # Output file
  if ($EM_OUTPUT_FILENAME eq "")
  {
    $EM_OUTPUT_FILENAME = $ENV{EM_OUTPUT_FILENAME};
    if ($EM_OUTPUT_FILENAME eq "")
    {
      $EM_OUTPUT_FILENAME = "$EMDW_HOME/sysman/log/emrepmgr.log.$$";
    }
  }

  $EM_ERROR_FILENAME = "$EM_OUTPUT_FILENAME.errors";

  # Export Dir
  if ($EM_EXPORT_DIR eq "")
  {
    $EM_EXPORT_DIR = $ENV{EM_EXPORT_DIR};
    if ($EM_EXPORT_DIR eq "")
    {
      $EM_EXPORT_DIR = "$EMDW_HOME/sysman/log";
    }
  }

  # Import Dir
  if ($EM_IMPORT_DIR eq "")
  {
    $EM_IMPORT_DIR = $ENV{EM_IMPORT_DIR};
    if ($EM_IMPORT_DIR eq "")
    {
      $EM_IMPORT_DIR = "$EMDW_HOME/sysman/log";
    }
  }

  if ($EM_VERBOSE gt 0)
  {
    $EM_ECHO_SQL = "ON";
  }
  else
  {
    $EM_ECHO_SQL = "OFF";
    $SQLPLUS = "$SQLPLUS -s ";
  }
  if ($DBCONTROL_HEADER != 1)
  {
	  if($OS_FLAG eq 1)
	  {
		  $EM_SYS_CREDENTIALS   = "SYS/ as SYSDBA";
	  }
	  else
	  {
		  $EM_SYS_CREDENTIALS   = "SYS/$EM_REPOS_DBSYSPWD\@$EM_REPOS_CONNSTRING AS SYSDBA";
	  }
	  $EM_REPOS_CREDENTIALS = "$EM_REPOS_USER/$EM_REPOS_PWD\@$EM_REPOS_CONNSTRING";
  }
}

sub dumpArguments()
{
    trace "Arguments : \n";
    trace "Connect String       = $EM_REPOS_CONNSTRING \n";
    trace "Action               = $EM_REPOS_ACTION \n";
    # trace "SYS password         = $EM_REPOS_DBSYSPWD \n";
    trace "Repos User           = $EM_REPOS_USER \n";
    # trace "Repos Password       = $EM_REPOS_PWD \n";
    trace "Default tablespace   = $EM_DEFAULT_TABLESPACE \n";
    trace "Default Data file    = $EM_DEFAULT_DATAFILE_NAME \n";
    trace "Dflt Dfile Init size = $EM_DEFAULT_DATAFILE_INIT_SIZE \n";
    trace "Dflt Dfile Ext size  = $EM_DEFAULT_DATAFILE_EXTEND_SIZE \n";
    trace "ECM tablespace       = $EM_ECM_TABLESPACE \n";
    trace "ECM Data file        = $EM_ECM_DATAFILE_NAME \n";
    trace "ECM Dfile Init size  = $EM_ECM_DATAFILE_INIT_SIZE \n";
    trace "ECM Dfile Ext size   = $EM_ECM_DATAFILE_EXTEND_SIZE \n";
    trace "ECM CSA tablespace       = $EM_ECM_CSA_TABLESPACE \n";
    trace "ECM CSA Data file        = $EM_ECM_CSA_DATAFILE_NAME \n";
    trace "ECM CSA Dfile Init size  = $EM_ECM_CSA_DATAFILE_INIT_SIZE \n";
    trace "ECM CSA Dfile Ext size   = $EM_ECM_CSA_DATAFILE_EXTEND_SIZE \n";
    trace "TEMP tablespace      = $EM_TEMP_TABLESPACE \n";
    trace "Create options       = $EM_CREATE_OPTIONS \n";
    trace "Verbose output       = $EM_VERBOSE \n";
    trace "Output File          = $EM_OUTPUT_FILENAME \n";
    # trace "SYS credentials      = $EM_SYS_CREDENTIALS \n";
    # trace "Repos user creds     = $EM_REPOS_CREDENTIALS \n";
    trace "Repos creation mode  = $EM_REPOS_MODE \n";
    trace "MetaLink user name   = $METALINK_USERNAME \n";
    # trace "MetaLink user password = $METALINK_PASSWORD \n";
    trace "MetaLink URL         = $METALINK_URL \n";
    trace "Export Directory     = $EM_EXPORT_DIR \n";
    trace "Import Directory     = $EM_IMPORT_DIR \n";
    trace "Path Separator       = $EM_PATH_SEP \n";
}

# check sys credentials..
sub checkSYSCredentials()
{
  if ( $DBCONTROL_HEADER != 1 && $NEED_SYS_CREDENTIAL == 1)
  {
  # Create a temp file..
  info "Checking SYS Credentials ... ";

  infoln "rem error switch";
  
  open(SQL_FILE,"|$SQLPLUS >> $EM_OUTPUT_FILENAME");

  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;


  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "OK.";
  }
  else
  {
    infoln "Failed";
  }
  infoln "rem error switch";

  return $rc;
}
  return 0;
}

sub dumpRepository()
{
	my $lda;
  info "Dumping repository ...\n";
	 if($OS_FLAG eq 1)
        {
         $lda = DBI->connect('dbi:Oracle:',"SYS"," ",{ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit =>0}) or (info "Could not connect OS Authenticated user" && exit 50);
        }
        else
        {

   $lda = DBI->connect('dbi:Oracle:', "SYS\@$EM_REPOS_CONNSTRING", "$EM_REPOS_DBSYSPWD",     {ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (info "Could not connect to SYS/$EM_REPOS_CONNSTRING: $DBI::errstr\n"        && exit 50);
	}
  my $sql_stmt = "SELECT object_name, object_type from all_objects where object_type in ('TABLE', 'TYPE', 'INDEX') and owner = '$EM_REPOS_USER' order by object_type, object_name";

  my $sql_cur = $lda->prepare($sql_stmt)
      or (info "prepare($sql_stmt): $DBI::errstr\n" and exit 51);

  $sql_cur->execute()
      or (info "sql_cur->execute(): $DBI::errstr\n" and exit 52);

  my @fetch_row;
  my @all_objects;
  my %object_count ;

  while (@fetch_row = $sql_cur->fetchrow_array())
  {
    my $array = () ;
    @$array = @fetch_row ;
    if($fetch_row[0] !~ /\$/ && $fetch_row[0] !~ /^SYS_/)
    {
      push(@all_objects,$array);
      $object_count{$fetch_row[1]}++;
    }
  }

  $sql_cur->finish() or info "sql_cur->finish(): $DBI::errstr\n";

  $lda->disconnect or info "disconnect $DBI::errstr\n";

  my $v ;
  my $k;

  open(OUTFILE,"> $EM_OUTPUT_FILENAME");
  print OUTFILE "\n\n********** Summary **********\n\n";
  while(($k,$v) = each(%object_count))
  {
    print OUTFILE "Total number of $k = $v\n";
  }
  print OUTFILE "\n\n";
  foreach $v (@all_objects)
  {
    my $h = $v->[0] ;
    my $t = $v->[1] ;
    print OUTFILE "$t\t $h\n";
  }
  print OUTFILE "\n\n********** End of Summary **********\n\n";

  close(OUTFILE);
  open(SQL_FILE,"|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_REPOS_CREDENTIALS \n";
  print SQL_FILE "set echo on \n";
  print SQL_FILE "column column_name format a48 \n";
  #print SQL_FILE "column column_position format a16 \n";

  foreach $v (@all_objects)
  {
    my $h = $v->[0] ;
    my $t = $v->[1] ;
    print SQL_FILE "select '$t' as type, '$h' as name from dual;\n" ;
    if($t eq 'INDEX' )
    {
      print SQL_FILE "select column_name , column_position from user_ind_columns where index_name = '$h';\n";
    }else
    {
      print SQL_FILE "desc $h\n";
    }
  }
  print SQL_FILE "exit;\n";
  
}
sub getReposVersion()
{
  my $rc = 0;
  my $lda;
  info "Getting EM repository Version ...\n";
   if($OS_FLAG eq 1)
        {
         $lda = DBI->connect('dbi:Oracle:',"SYS"," ",{ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit =>0}) or (info "Could not connect OS Authenticated user" && exit 50);
        }
        else
        {

   $lda = DBI->connect('dbi:Oracle:', "SYS\@$EM_REPOS_CONNSTRING", "$EM_REPOS_DBSYSPWD",  {ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit => 0})  or (info "Could not connect to SYS/$EM_REPOS_CONNSTRING: $DBI::errstr\n"   && exit 50);
	} 
 
  my $sql_stmt = "SELECT version FROM $EM_REPOS_USER.mgmt_versions WHERE component_name='CORE'";

  my $sql_cur = $lda->prepare($sql_stmt)
      or (info "prepare($sql_stmt): $DBI::errstr\n" and exit 51);

  $sql_cur->execute()
      or (info "sql_cur->execute(): $DBI::errstr\n" and exit 52);

  my @fetch_row;
  my $repos_version;

  if (@fetch_row = $sql_cur->fetchrow_array())
  {
    $repos_version = $fetch_row[0];
  }
  else 
  {  
    # should not happen
    info "Cursor returned no rows\n";
    exit 53;
  }

  $sql_cur->finish() or info "sql_cur->finish(): $DBI::errstr\n";

  $lda->disconnect or info "disconnect $DBI::errstr\n";

  info "Repository version: $repos_version\n";

  return $repos_version;
}

#
# If TEMP is a valid temporary tablespace, it returns it. Otherwise, it returns
# any other valid temporary tablespace.
#
sub getTempTablespace()
{
  info "Getting temporary tablespace from database...\n";
  my $lda;
	 if($OS_FLAG eq 1)
        {
         $lda = DBI->connect('dbi:Oracle:',"SYS"," ",{ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit =>0}) or (info "Could not connect OS Authenticated user,$DBI::errstr" && exit 50);
        }
        else
        {

   $lda = DBI->connect('dbi:Oracle:', "SYS@".$EM_REPOS_CONNSTRING, "$EM_REPOS_DBSYSPWD",    {ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (info "Could not connect to SYS/$EM_REPOS_CONNSTRING: $DBI::errstr\n"        && exit 50);
	}

  my $sql_stmt = "SELECT tablespace_name FROM dba_tablespaces WHERE contents='TEMPORARY' "
                 ." AND status='ONLINE'";

  my $sql_cur = $lda->prepare($sql_stmt)
      or (info "prepare($sql_stmt): $DBI::errstr\n" and exit 51);
  $sql_cur->execute()
      or (info "sql_cur->execute(): $DBI::errstr\n" and exit 52);

  my @fetch_row;
  my $tablespace = "";
  while (@fetch_row = $sql_cur->fetchrow_array())
  {
    $tablespace = $fetch_row[0];
    if ($tablespace eq "TEMP")
    { 
      last;
    }
  }

  $sql_cur->finish() or info "sql_cur->finish(): $DBI::errstr\n";

  $lda->disconnect or info "disconnect $DBI::errstr\n";

  if ($tablespace eq "") 
  {  
    info "Database does not have any temporary tablespaces ONLINE.\n";
    exit 54;
  }

  info "Found temporary tablespace: $tablespace\n";

  return $tablespace;
}

#
# Check that the input tablespace is a valid temporary tablespace.
#
sub validateTempTablespace($)
{
  my ($tablespace) = shift;
  my $lda;
  info "Validating temporary tablespace: $tablespace\n";
	 if($OS_FLAG eq 1)
        {
         $lda = DBI->connect('dbi:Oracle:',"SYS"," ",{ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit =>0}) or (info "Could not connect OS Authenticated user" && exit 50);
        }
        else
        {

   $lda = DBI->connect('dbi:Oracle:', "SYS@".$EM_REPOS_CONNSTRING, "$EM_REPOS_DBSYSPWD",  {ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (info "Could not connect to SYS/$EM_REPOS_CONNSTRING: $DBI::errstr\n"        && exit 50);
	}
my $sql_stmt = "SELECT status FROM dba_tablespaces WHERE contents='TEMPORARY' and tablespace_name = '$tablespace'";

  my $sql_cur = $lda->prepare($sql_stmt)
      or (info "prepare($sql_stmt): $DBI::errstr\n" and exit 51);
  $sql_cur->execute()
      or (info "sql_cur->execute(): $DBI::errstr\n" and exit 52);

  my @fetch_row;
  my $status = "";
  if (@fetch_row = $sql_cur->fetchrow_array())
  {
    $status = $fetch_row[0];
  }

  $sql_cur->finish() or info "sql_cur->finish(): $DBI::errstr\n";

  $lda->disconnect or info "disconnect $DBI::errstr\n";

  if ($status eq "") 
  {  
    info "Temporary tablespace does not exist: $tablespace\n";
    exit 55;
  }
  elsif($status ne "ONLINE")
  {
    info "Temporary tablespace is not ONLINE: $tablespace\n";
    exit 56;
  }

  info "Found temporary tablespace: $tablespace\n";
}

sub checkDBInitParams()
{
  # Create a temp file..
  info "Checking DB Init Parameters ... ";
  infoln "rem error switch";

  open(SQL_FILE,"|$SQLPLUS >> $EM_OUTPUT_FILENAME");

  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_check_init_parms.sql \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $?;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "OK.";
  }
  else
  {
    infoln "Failed";
  }
  infoln "rem error switch";

  return $rc;
}

sub validateReposUser()
{
  info "Validating for Repos User ...";
  # Create a temp file..

  open(SQL_FILE,"|$SQLPLUS >> $EM_OUTPUT_FILENAME");

  print SQL_FILE "$EM_REPOS_CREDENTIALS \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
	infoln "OK.";
  }
  else
  {
	infoln "Failed";
  }

  return $rc;
}

sub checkReposUser()
{
  # Create a temp file..
  info "Checking for Repos User ... ";

  open(SQL_FILE, "|$SQLPLUS > $devNull");

  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_check_repos_user.sql $EM_REPOS_USER EXISTS \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $?;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Exists.";
  }
  else
  {
    infoln "Does not Exist.";
  }

  return $rc;
}

sub loadNecessaryObjects()
{
  my $objExists = 0;

  infoln "Loading necessary DB objects ... ";


  # Check SPOOL, LDAP, RLS and JAVAVM..
  $objExists = checkDBMSPOOL();
  my $rc = 0;
  if ($objExists eq 0)
  {
    infoln "DBMS POOL package exists.";
  }
  else
  {
    infoln "DBMS POOL package does not exist. So adding";
    open(LN_SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  
    print LN_SQL_FILE "$EM_SYS_CREDENTIALS \n";
    print LN_SQL_FILE "set echo $EM_ECHO_SQL \n";
    print LN_SQL_FILE "set verify $EM_ECHO_SQL \n";
    print LN_SQL_FILE "set feedback $EM_ECHO_SQL \n";

    print LN_SQL_FILE "\@$ORACLE_HOME/rdbms/admin/dbmspool.sql \n";
    print LN_SQL_FILE "exit;\n";
    close LN_SQL_FILE;

    $rc = 0xffff & $?;
    $rc >>= 8;
  }

#  $objExists = checkLDAP();
#  if ($objExists eq 0)
#  {
#    infoln "DBMS LDAP package exists.";
#  } else {
#    infoln "DBMS LDAP package does not exist. So adding.";
#    print LN_SQL_FILE "\@$ORACLE_HOME/rdbms/admin/catldap.sql \n";
#  }
#
#  $objExists = checkRLS();
#  if ($objExists eq 0)
#  {
#    infoln "DBMS RLS package exists.";
#  } else {
#    infoln "DBMS RLS package does not exist. So adding.";
#    print LN_SQL_FILE "\@$ORACLE_HOME/rdbms/admin/catrls.sql \n";
#  }

#  $objExists = checkJAVAVM();
#  if ($objExists eq 0)
#  {
#    infoln "JAVAVM exists.";
#  } else {
#    infoln "JAVAVM does not exist. So adding.";
#    print LN_SQL_FILE "\@$ORACLE_HOME/javavm/install/initjvm.sql \n";
#  }


  traceln "Return code = $rc.";
  infoln "Done Loading necessary DB objects";

  return $rc;
}

sub checkObject($$)
{
  my ($db_obj_name, $db_obj_type) = @_;
  # Create a temp file..
  info "Checking DB Object ($db_obj_name , $db_obj_type) ... ";
  infoln "rem error switch";

  open(SQL_FILE, "|$SQLPLUS > $devNull");

  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo off \n";
  print SQL_FILE "set verify off \n";
  print SQL_FILE "set feedback off \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_check_object.sql $db_obj_name $db_obj_type \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Exists.";
  }
  else
  {
    infoln "Does not exist.";
  }
  infoln "rem error switch";

  return $rc;
}

sub checkDBMSPOOL()
{
  return checkObject("DBMS_SHARED_POOL", "PACKAGE");
}

sub checkLDAP()
{
  return checkObject("DBMS_LDAP", "PACKAGE");
}

sub checkRLS()
{
  return checkObject("DBA_POLICIES", "VIEW");
}

sub checkJAVAVM()
{
  # Create a temp file..
  info "Checking JAVA VM option ... ";

  open(SQL_FILE, "|$SQLPLUS > $devNull");

  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_check_javavm.sql \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $?;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Exists.";
  }
  else
  {
    infoln "Does not exist.";
  }

  return $rc;
}

# Create Synonyms
# Create tablespace
# Create Repos User.
sub createReposUser()
{
  # Create a temp file..
  info "Creating repos user ... ";
  infoln "rem error switch";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo on \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_error_switch.sql\n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print SQL_FILE "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print SQL_FILE "DEFINE EM_REPOS_PWD = $EM_REPOS_PWD \n";
  print SQL_FILE "DEFINE EM_REPOS_MODE = $EM_REPOS_MODE \n";
  print SQL_FILE "DEFINE EM_TEMP_TABLESPACE = $EM_TEMP_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_DEFAULT_TABLESPACE_NAME = $EM_DEFAULT_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_DEFAULT_DATAFILE_NAME = $EM_DEFAULT_DATAFILE_NAME \n";
  print SQL_FILE "DEFINE EM_DEFAULT_DATAFILE_SIZE = $EM_DEFAULT_DATAFILE_INIT_SIZE \n";
  print SQL_FILE "DEFINE EM_DEFAULT_DATAFILE_EXTD_SIZE = $EM_DEFAULT_DATAFILE_EXTEND_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_TABLESPACE_NAME = $EM_ECM_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_DATAFILE_NAME = $EM_ECM_DATAFILE_NAME \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_DATAFILE_SIZE = $EM_ECM_DATAFILE_INIT_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_DATAFILE_EXT_SIZE = $EM_ECM_DATAFILE_EXTEND_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_TABLESPACE_NAME = $EM_ECM_CSA_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_DATAFILE_NAME = $EM_ECM_CSA_DATAFILE_NAME \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_DATAFILE_SIZE = $EM_ECM_CSA_DATAFILE_INIT_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_DATAFILE_EXT_SIZE = $EM_ECM_CSA_DATAFILE_EXTEND_SIZE \n";
  print SQL_FILE "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_create_synonyms.sql \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_create_tablespaces.sql";
  print SQL_FILE " $EM_DEFAULT_TABLESPACE ";
  print SQL_FILE " $EM_DEFAULT_DATAFILE_NAME ";
  print SQL_FILE " $EM_DEFAULT_DATAFILE_INIT_SIZE ";
  print SQL_FILE " $EM_DEFAULT_DATAFILE_EXTEND_SIZE ";
  print SQL_FILE " $EM_ECM_TABLESPACE ";
  print SQL_FILE " $EM_ECM_DATAFILE_NAME ";
  print SQL_FILE " $EM_ECM_DATAFILE_INIT_SIZE ";
  print SQL_FILE " $EM_ECM_DATAFILE_EXTEND_SIZE ";
  print SQL_FILE " $EM_ECM_CSA_TABLESPACE ";
  print SQL_FILE " $EM_ECM_CSA_DATAFILE_NAME ";
  print SQL_FILE " $EM_ECM_CSA_DATAFILE_INIT_SIZE ";
  print SQL_FILE " $EM_ECM_CSA_DATAFILE_EXTEND_SIZE \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_create_repos_user.sql";
  print SQL_FILE " $EM_REPOS_USER ";
  print SQL_FILE " $EM_REPOS_PWD ";
  print SQL_FILE " $EM_DEFAULT_TABLESPACE ";
  print SQL_FILE " $EM_TEMP_TABLESPACE ";
  print SQL_FILE " $EM_REPOS_MODE ";
  print SQL_FILE " $EM_ECHO_SQL\n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub setDefaultTblSpace($)
{
  my $dflt_tblspc = shift;
  info "Setting Default tablespace ... ";
  trace "Dflt tbl spc - $dflt_tblspc. ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");

  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "ALTER USER $EM_REPOS_USER DEFAULT TABLESPACE $dflt_tblspc;\n";
  print SQL_FILE "/\n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

# Set default tablspace
# Load java.
# Reset default tablespace
sub loadjars()
{
  my $rc = setDefaultTblSpace $EM_ECM_TABLESPACE ;

  info "Loading Jar file ... ";
  $rc = 0xffff & system("$LOADJAVA -user \"$EM_REPOS_CREDENTIALS\" -synonym -resolve -verbose $EM_LOADJAVA_JAR_ROOT/emdloader.jar");
  $rc >>= 8;

  if ($rc eq 0)
  {
    infoln "Done";
  }
  else
  {
    infoln "Failed";
    return $rc;
  }

  $rc = setDefaultTblSpace $EM_DEFAULT_TABLESPACE ;

  return $rc;
}

# Perform the following
# Creation
# Initialization
# Out-of-box initialization
sub createEMSchema()
{

  info "Creating EM Schema ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");

  print SQL_FILE "$EM_REPOS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print SQL_FILE "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print SQL_FILE "DEFINE EM_REPOS_PWD = $EM_REPOS_PWD \n";
  print SQL_FILE "DEFINE EM_REPOS_MODE = $EM_REPOS_MODE \n";
  print SQL_FILE "DEFINE EM_TEMP_TABLESPACE = $EM_TEMP_TABLESPACE \n";
  print SQL_FILE "DEFINE ORACLE_HOME = $ORACLE_HOME \n";
  print SQL_FILE "DEFINE EM_PATH_SEP = $EM_PATH_SEP \n";
  print SQL_FILE "DEFINE EM_DEFAULT_TABLESPACE_NAME = $EM_DEFAULT_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_DEFAULT_DATAFILE_NAME = $EM_DEFAULT_DATAFILE_NAME \n";
  print SQL_FILE "DEFINE EM_DEFAULT_DATAFILE_SIZE = $EM_DEFAULT_DATAFILE_INIT_SIZE \n";
  print SQL_FILE "DEFINE EM_DEFAULT_DATAFILE_EXTD_SIZE = $EM_DEFAULT_DATAFILE_EXTEND_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_TABLESPACE_NAME = $EM_ECM_TABLESPACE \n";
  #Some script refer to EM_ECM_DEPOT_TABLESPACE. Define that here.
  print SQL_FILE "DEFINE EM_ECM_DEPOT_TABLESPACE = $EM_ECM_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_DATAFILE_NAME = $EM_ECM_DATAFILE_NAME \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_DATAFILE_SIZE = $EM_ECM_DATAFILE_INIT_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_DEPOT_DATAFILE_EXT_SIZE = $EM_ECM_DATAFILE_EXTEND_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_TABLESPACE_NAME = $EM_ECM_CSA_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_DATAFILE_NAME = $EM_ECM_CSA_DATAFILE_NAME \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_DATAFILE_SIZE = $EM_ECM_CSA_DATAFILE_INIT_SIZE \n";
  print SQL_FILE "DEFINE EM_ECM_CSA_DATAFILE_EXT_SIZE = $EM_ECM_CSA_DATAFILE_EXTEND_SIZE \n";
  print SQL_FILE "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
 
  my $se = "";
  
  if(defined $ENV{'USE_NEW_REPMGR'} && $ENV{'USE_NEW_REPMGR'} eq 'true')
  {
    infoln "using new rep manager framework\n";
    $se = "_" ;
  }

  if ($EM_CREATE_OPTIONS & $EM_CREATE_SEEDDB)
  {
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/${se}core_cre.sql $EM_ECM_TABLESPACE $EM_REPOS_USER $EM_ECM_CSA_TABLESPACE\n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/db/latest/${se}db_cre.sql $EM_ECM_TABLESPACE \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/db/latest/${se}db_cre.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ias/latest/${se}ias_cre.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ias/latest/${se}ias_cre.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/pa/latest/${se}pa_cre.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/pa/latest/${se}pa_cre.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ocs/latest/${se}ocs_cre.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ocs/latest/${se}ocs_cre.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ci/latest/${se}ci_cre.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ci/latest/${se}ci_cre.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/pp/latest/_pp_cre.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/pp/latest/_pp_cre.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_recompile_invalid.sql";
    print SQL_FILE " $EM_REPOS_USER \n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_pin_plsql.sql \n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/${se}core_init.sql";
    print SQL_FILE " $EM_REPOS_USER $EM_REPOS_PWD $EM_REPOS_MODE $EM_ECHO_SQL\n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/db/latest/${se}db_init.sql $EM_REPOS_USER\n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/db/latest/${se}db_init.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ias/latest/${se}ias_init.sql $EM_REPOS_USER\n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ias/latest/${se}ias_init.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/pa/latest/${se}pa_init.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/pa/latest/${se}pa_init.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ocs/latest/${se}ocs_init.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ocs/latest/${se}ocs_init.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ci/latest/${se}ci_init.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ci/latest/${se}ci_init.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/pp/latest/_pp_init.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/pp/latest/_pp_init.sql" );
    print SQL_FILE "commit;\n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/user_model/user_create_view_user.sql";
    print SQL_FILE " $EM_REPOS_PWD";
    print SQL_FILE " $EM_ECHO_SQL";
    print SQL_FILE " $EM_REPOS_USER\n";
  }

  if ($EM_CREATE_OPTIONS & $EM_CREATE_OUTOFBOX)
  {
    print SQL_FILE "DEFINE METALINK_USERNAME = $METALINK_USERNAME \n";
    print SQL_FILE "DEFINE METALINK_PASSWORD = $METALINK_PASSWORD \n";
    print SQL_FILE "DEFINE METALINK_URL = $METALINK_URL \n";
    print SQL_FILE "\@$EMDW_HOME/sysman/emdrep/config/repository.variables.template \n";
    print SQL_FILE "\@$EMDW_HOME/sysman/emdrep/config/repository.variables \n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/${se}core_outofbox.sql $EM_REPOS_USER \n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/db/latest/${se}db_outofbox.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/db/latest/${se}db_outofbox.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ias/latest/${se}ias_outofbox.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ias/latest/${se}ias_outofbox.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/ci/latest/${se}ci_outofbox.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/ci/latest/${se}ci_outofbox.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/pp/latest/_pp_outofbox.sql \n"
            if ( -e  "$EM_SQL_SCRIPT_ROOT/pp/latest/_pp_outofbox.sql" );
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_submit_dbms_jobs.sql \n";
    print SQL_FILE "EXECUTE EMD_MAINTENANCE.SET_COMP_STATUS('CORE', EMD_MAINTENANCE.G_STATUS_CONFIGURED_READY); \n";
    print SQL_FILE "COMMIT; \n";
  }
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $?;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  if ($EM_CREATE_OPTIONS & $EM_CREATE_OUTOFBOX)
  {
    #run transx only if repository creation is completed
    if($rc eq 0)
    {
       &execTransX;
    }
  }

  return $rc;
}

sub setComponentConditions
{
 my $compRef = shift;
 $compRef->setCondition('EM_REPOS_MODE',$EM_REPOS_MODE);
 # the default component behavior is to have no test_metadata option
 $compRef->setOptionalCondition('TEST_METADATA', 'FALSE');
}


sub createEMSchemaNew()
{

  info "Creating EM Schema ... ";
  infoln "using new rep manager framework\n";

  my $fh = IO::Handle->new();
  my $session ;
  #my $logger = Logger->new();

  if(defined $DRY_RUN && $DRY_RUN eq 'true')
  {
    open($fh, "> $EM_OUTPUT_FILENAME".".dryrun");
  }else
  {
    if ($DBCONTROL_HEADER != 1)
    {
    infoln "rem error switch";
    open($fh, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
    } else {
      open($fh, "> $DBCONTROL_SQLROOT/dbcontrol_sa.sql");
  }
  }

  $session = ScriptSession->new($fh);

  if ( $DBCONTROL_HEADER != 1) 
  {
  print $fh "$EM_REPOS_CREDENTIALS \n";
  print $fh "set echo on \n";
  print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_error_switch.sql\n";
  print $fh "set echo $EM_ECHO_SQL \n";
  print $fh "set verify $EM_ECHO_SQL \n";
  print $fh "set feedback $EM_ECHO_SQL \n";
  print $fh "$EM_SQL_ERR_EXIT \n";
  print $fh "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print $fh "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print $fh "DEFINE EM_REPOS_PWD = $EM_REPOS_PWD \n";
  print $fh "DEFINE EM_REPOS_MODE = $EM_REPOS_MODE \n";
  print $fh "DEFINE EM_TEMP_TABLESPACE = $EM_TEMP_TABLESPACE \n";
  print $fh "DEFINE ORACLE_HOME = $ORACLE_HOME \n";
  print $fh "DEFINE EM_PATH_SEP = $EM_PATH_SEP \n";
  print $fh "DEFINE EM_DEFAULT_TABLESPACE_NAME = $EM_DEFAULT_TABLESPACE \n";
  print $fh "DEFINE EM_DEFAULT_DATAFILE_NAME = $EM_DEFAULT_DATAFILE_NAME \n";
  print $fh "DEFINE EM_DEFAULT_DATAFILE_SIZE = $EM_DEFAULT_DATAFILE_INIT_SIZE \n";
  print $fh "DEFINE EM_DEFAULT_DATAFILE_EXTD_SIZE = $EM_DEFAULT_DATAFILE_EXTEND_SIZE \n";
  print $fh "DEFINE EM_ECM_DEPOT_TABLESPACE_NAME = $EM_ECM_TABLESPACE \n";
  #Some script refer to EM_ECM_DEPOT_TABLESPACE. Define that here.
  print $fh "DEFINE EM_ECM_DEPOT_TABLESPACE = $EM_ECM_TABLESPACE \n";
  print $fh "DEFINE EM_ECM_DEPOT_DATAFILE_NAME = $EM_ECM_DATAFILE_NAME \n";
  print $fh "DEFINE EM_ECM_DEPOT_DATAFILE_SIZE = $EM_ECM_DATAFILE_INIT_SIZE \n";
  print $fh "DEFINE EM_ECM_DEPOT_DATAFILE_EXT_SIZE = $EM_ECM_DATAFILE_EXTEND_SIZE \n";
  print $fh "DEFINE EM_ECM_CSA_TABLESPACE_NAME = $EM_ECM_CSA_TABLESPACE \n";
  print $fh "DEFINE EM_ECM_CSA_DATAFILE_NAME = $EM_ECM_CSA_DATAFILE_NAME \n";
  print $fh "DEFINE EM_ECM_CSA_DATAFILE_SIZE = $EM_ECM_CSA_DATAFILE_INIT_SIZE \n";
  print $fh "DEFINE EM_ECM_CSA_DATAFILE_EXT_SIZE = $EM_ECM_CSA_DATAFILE_EXTEND_SIZE \n";
  print $fh "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  }

  my $repo = Repository->new();
  #$repo->setLogger($logger);
  $repo->init($EM_SQL_SCRIPT_ROOT);
  my $h ;
  my @comps = $repo->getComponentsOrdered();
  foreach $h (@comps)
  {
    infoln "parsing component ".$h->getName()."\n";
    $h->parse();
    if ($NO_CONDITION == 0) {
      setComponentConditions($h);
    }
  }  
  
  if (($EM_CREATE_OPTIONS & $EM_CREATE_SEEDDB) || ($EM_CREATE_OPTIONS & $EM_CREATE_LOCALDB))
  {    
    foreach $h (@comps)
    {
      infoln "executing ".$h->getName()." creation scripts\n";
      $h->create($session);
    }    
        
    print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_recompile_invalid.sql";    
    if ( $DBCONTROL_HEADER != 1)
    {
    print $fh " $EM_REPOS_USER \n";    
    print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_pin_plsql.sql \n";
    }
    else
    {
      print $fh " &EM_REPOS_USER \n";
    }
    
    if ( $DBCONTROL_HEADER == 1)
    {
      # need to set the context
      print $fh "EXECUTE &EM_REPOS_USER..setEMUserContext('&EM_REPOS_USER',1); \n";
    }
    
    foreach $h (@comps)
    {
      infoln "executing ".$h->getName()." post_creation scripts \n";
      $h->post_create($session);
      my $cname = uc $h->getName();
      my $newver = $h->getVersion();
      if ( $DBCONTROL_HEADER != 1)
      {
      print $fh "EXECUTE EMD_MAINTENANCE.SET_VERSION('$cname', '$newver', '$newver', '$EM_REPOS_MODE');\n";
      } else 
      {
        print $fh "EXECUTE EMD_MAINTENANCE.SET_VERSION('$cname', '$newver', '$newver', '&EM_REPOS_MODE');\n";
    }    
    }    
        
    print $fh "commit;\n";    
    
    if ($DBCONTROL_HEADER != 1)
    {
    print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/user_model/user_create_view_user.sql";    
    print $fh " $EM_REPOS_PWD";
    print $fh " $EM_ECHO_SQL";
    print $fh " $EM_REPOS_USER\n";
  }
  }

  if ($EM_CREATE_OPTIONS & $EM_CREATE_OUTOFBOX)
  {
    if ($DBCONTROL_HEADER != 1)
    {
    print $fh "DEFINE METALINK_USERNAME = $METALINK_USERNAME \n";
    print $fh "DEFINE METALINK_PASSWORD = $METALINK_PASSWORD \n";
    print $fh "DEFINE METALINK_URL = $METALINK_URL \n";
    print $fh "\@$EMDW_HOME/sysman/emdrep/config/repository.variables.template \n";
    print $fh "\@$EMDW_HOME/sysman/emdrep/config/repository.variables \n";

    foreach $h (@comps)
    {
      infoln "executing ".$h->getName()." outofbox scripts \n";
      $h->outofbox($session);
    }    
        
    print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_submit_dbms_jobs.sql \n";
    print $fh "EXECUTE EMD_MAINTENANCE.SET_COMP_STATUS('CORE', EMD_MAINTENANCE.G_STATUS_CONFIGURED_READY); \n";
    print $fh "COMMIT; \n";
  print $fh "exit;\n";
    } else {
      my $oob_fh = IO::Handle->new();
      open($oob_fh, "> $DBCONTROL_SQLROOT/dbcontrol_oob.sql");
      my $oob_session = ScriptSession->new($oob_fh);    
      foreach $h (@comps)
      {
        infoln "executing ".$h->getName()." outofbox scripts \n";
        $h->outofbox($oob_session);
      }
      close $oob_fh;
    }
  }
  close $fh;

  my $rc = 0xffff & $?;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    #run metadata
    &execMetadata;
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  if ($EM_CREATE_OPTIONS & $EM_CREATE_OUTOFBOX)
  {
    #run transx only if repository creation is completed
    if($rc eq 0)
    {
       if(!defined $DRY_RUN || $DRY_RUN ne 'true')
       {
         # skipping transX when in create_in_sysaux
         if ($EM_REPOS_ACTION ne "create_in_sysaux")
         {
           &execTransX;
         }
       }
    }
  }

  return $rc;
}


sub createEMSchemaInLocalDB()
{

  info "Creating EM Schema in local db ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  # print SQL_FILE "connect sys/$EM_REPOS_DBSYSPWD as sysdba \n";
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/emreposcre.sql";
  print SQL_FILE " $EMDW_HOME $EM_REPOS_USER ";
  print SQL_FILE " $EM_REPOS_PWD $EM_TEMP_TABLESPACE $EM_ECHO_SQL\n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/emreposoutofbox.sql";
  print SQL_FILE " $EMDW_HOME $EM_REPOS_USER \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

# obsoleted.
sub registerEMJobType($)
{
  my ($emJobTypeFile) = @_;

  my $rc = 0xffff & system("$ORACLE_HOME/bin/emutil register jobtype $emJobTypeFile $EM_REPOS_USER $EM_REPOS_PWD \"$EM_REPOS_CONNSTRING\"");
  $rc >>= 8;

  return $rc;
}

# obsoleted.
sub registerEMJobTypes()
{
  my $rc = 0;
  my @emJobTypes = (
      "$EM_JOBTYPES_ROOT/OSCommand.xml",
      "$EM_JOBTYPES_ROOT/ConfirmEMDDown.xml",
      "$EM_JOBTYPES_ROOT/patchNotify.xml",
      "$EM_JOBTYPES_ROOT/CloneIASToInstances.xml",
      "$EM_JOBTYPES_ROOT/CloneIASToNewInstance.xml",
      "$EM_JOBTYPES_ROOT/CloneIASToNewInstallation.xml",
      "$EM_JOBTYPES_ROOT/liveSnapshotCollectionCommand.xml",
      "$EM_JOBTYPES_ROOT/SQLScript.xml",
      "$EM_JOBTYPES_ROOT/StageDatabasePatch.xml",
      "$EM_JOBTYPES_ROOT/StageDatabasePatchTargets.xml",
      "$EM_JOBTYPES_ROOT/PatchDatabase.xml",
      "$EM_JOBTYPES_ROOT/PatchDatabaseTargets.xml",
      "$EM_JOBTYPES_ROOT/PatchAgent.xml",
      "$EM_JOBTYPES_ROOT/PatchAgentTargets.xml",
      "$EM_JOBTYPES_ROOT/UpdateARUTables.xml",
      "$EM_JOBTYPES_ROOT/DBClone.xml",
      "$EM_JOBTYPES_ROOT/Export.xml",
      "$EM_JOBTYPES_ROOT/Import.xml",
      "$EM_JOBTYPES_ROOT/Load.xml",
      "$EM_JOBTYPES_ROOT/Rman.xml",
      "$EM_JOBTYPES_ROOT/Backup.xml",
      "$EM_JOBTYPES_ROOT/SuggestedBackup.xml",
      "$EM_JOBTYPES_ROOT/DBConfig.xml",
      "$EM_JOBTYPES_ROOT/Reorganize.xml",
      "$EM_JOBTYPES_ROOT/AddTargetJob.xml",
      "$EM_JOBTYPES_ROOT/ReloadTargetProperties.xml",
      "$EM_JOBTYPES_ROOT/DeleteTargetJob.xml",
      "$EM_JOBTYPES_ROOT/StartBlackoutJob.xml",
      "$EM_JOBTYPES_ROOT/EndBlackoutJob.xml",
      "$EM_JOBTYPES_ROOT/StopBlackoutJob.xml",
      "$EM_JOBTYPES_ROOT/EditBlackoutJob.xml",
      "$EM_JOBTYPES_ROOT/DiscardStateJob.xml"
    );

  foreach my $emJobType (@emJobTypes) {

    if ( -e "$emJobType" )
    {
       $rc = registerEMJobType($emJobType);
       if ($rc ne 0)
       {
         print "Failed registering Job type file $emJobType. \n";
         return $rc;
       }
    }
    else
    {
      print "Job type file $emJobType does not exist. \n";
    }

  }
  return $rc;
}

sub checkForErrors()
{
  my $errFound = 0;
  # Check the output file for errors
  my $erroron = 1;
  open(OUTPUT_FILE, "$EM_OUTPUT_FILENAME");
  while (<OUTPUT_FILE>)
  {
    if (/rem error switch/)
    {
        if ($erroron eq 1)
        {
          $erroron = 0;
        } else {
          $erroron = 1;
        }
    }

    # Check for ORA- or Warning: in lines that dont have Rem or --
    if ( ($erroron eq 1 && (/ORA-.*:/)) || 
         ($erroron eq 1 && (/Warning: /)) || 
         (/^SP2/) )
    {
      if ( (/Rem/) || (/--/) )
      {
      }
      else
      {
        if ($EM_REPOS_ACTION eq 'create_in_sysaux')
        {
          if ( (/db\/db_/) )
          {
          }
          else
          {
            print STDERR $_;
            $errFound = 1;
          }
        }
        else
        {
          print STDERR $_;
          $errFound = 1;
        }
      }
    }
  }
  close OUTPUT_FILE;

  return $errFound;
}

### Drop Routines.
sub quiesceDB()
{
  # Create a temp file..
  info "Quiescing DB ... ";

  open(SQL_FILE, "|$SQLPLUS > $devNull");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "ALTER SYSTEM QUIESCE RESTRICTED;\n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $?;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub clearContexts()
{
  # Create a temp file..
  info "Clearing EM Contexts ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "EXEC $EM_REPOS_USER.setEMUserContext('', 5);\n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $?;
  $rc >>= 8;

  traceln "Clearing contexts. Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "OK.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub dropEMUsers()
{
  # Create a temp file..
  infoln "Dropping EM users ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "set serveroutput on size 5000 \n";
  print SQL_FILE "$EM_SQL_ERR_CONT \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_drop_users.sql $EM_REPOS_USER \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  traceln "Drop EM Users. Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub dropReposUser()
{
  # Create a temp file..
  info "Dropping Repos User ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "set serveroutput $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_CONT \n";
  print SQL_FILE "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_drop_repos_user.sql $EM_REPOS_USER \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  traceln "Drop Repos User. Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub dropRoles()
{
  # Create a temp file..
  info "Dropping Roles/Synonymns/Tablespaces ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_drop_synonyms.sql \n";
  # Not calling this as part of fix in sktedla_rfi_backport_4726892_10.2.0.4
  # Now, tablespaces are dropped as part of admin_drop_repos_user.sql
  #print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_drop_tablespaces.sql \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub unquieseDB()
{
  # Create a temp file..
  info "Unquiescing DB ... ";

  open(SQL_FILE, "|$SQLPLUS > $devNull");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "ALTER SYSTEM UNQUIESCE;\n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace " Return code = $rc.";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub setSchemaStatus
{
  my ($comp, $status) = @_ ;
  my $pkg_status = 'EMD_MAINTENANCE.G_STATUS_INITIALIZING';
  if ($status == 1)
  {
    $pkg_status = 'EMD_MAINTENANCE.G_STATUS_INITIALIZED';
  } elsif ($status == 2)
  {
    $pkg_status = 'EMD_MAINTENANCE.G_STATUS_UPGRADING';
  } elsif ($status == 3)
  {
    $pkg_status = 'EMD_MAINTENANCE.G_STATUS_UPGRADED';
  } elsif ($status == 4)
  {
    $pkg_status = 'EMD_MAINTENANCE.G_STATUS_CONFIGURED_READY';
  }
  my $statement = "BEGIN EMD_MAINTENANCE.SET_VERSION('$comp','0','0','SYSTEM',$pkg_status);END;";
  infoln "Running setSchemaStatus: $statement\n";
  my $lda = DBI->connect('dbi:Oracle:', "$EM_REPOS_USER\@$EM_REPOS_CONNSTRING", "$EM_REPOS_PWD",     {ora_session_mode => 0, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (info "Could not connect to $EM_REPOS_USER/$EM_REPOS_CONNSTRING: $DBI::errstr\n"        && exit 50);
  my $sql_cur = $lda->prepare($statement)
      or (info "prepare($statement): $DBI::errstr\n" and exit 51);

  $sql_cur->execute()
      or (info "sql_cur->execute(): $DBI::errstr\n" and exit 52);

  $sql_cur->finish() or info "sql_cur->finish(): $DBI::errstr\n";

  $lda->disconnect or info "disconnect $DBI::errstr\n";

  return 0;
}

## generic query routine

sub executeQuery
{
  my ($query, $as_sysman) = @_ ;
    
  info "executing query : \n  \"$query\"\n";

  my $lda ; 
  if(defined $as_sysman && $as_sysman eq 'true' )
  {
    $lda = DBI->connect('dbi:Oracle:', "$EM_REPOS_USER\@$EM_REPOS_CONNSTRING", "$EM_REPOS_PWD",     {ora_session_mode => 0, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (info "Could not connect to SYS/$EM_REPOS_CONNSTRING: $DBI::errstr\n"        && exit 50);
  }else
  {
    $lda = DBI->connect('dbi:Oracle:', "SYS\@$EM_REPOS_CONNSTRING", "$EM_REPOS_DBSYSPWD",     {ora_session_mode => 2, PrintError => 0, RaiseError => 0, AutoCommit => 0})    or (info "Could not connect to SYS/$EM_REPOS_CONNSTRING: $DBI::errstr\n"        && exit 50);
  }
    
  my $sql_cur = $lda->prepare($query)
      or (info "prepare($query): $DBI::errstr\n" and exit 51);

  $sql_cur->execute()
      or (info "sql_cur->execute(): $DBI::errstr\n" and exit 52);

  my @fetch_row;
  my $result_set = ();

  while (@fetch_row = $sql_cur->fetchrow_array())
  {
    my $array = () ;
    @$array = @fetch_row ;
    push(@$result_set,$array);
  }

  $sql_cur->finish() or info "sql_cur->finish(): $DBI::errstr\n";

  $lda->disconnect or info "disconnect $DBI::errstr\n";
  
  return $result_set ;

}


### Upgrade routines.

sub upgradeEMSchemaNew()
{
  info "Upgrading EM Schema ... ";
  infoln "using new rep manager framework\n";

  my $h;
  my $fh = IO::Handle->new();
  my $session ;
  #my $logger = Logger->new();

  if(defined $DRY_RUN && $DRY_RUN eq 'true')
  {
    open($fh, "> $EM_OUTPUT_FILENAME".".dryrun");
  }else
  {
    infoln "rem error switch\n";
    open($fh, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  }
  $session = ScriptSession->new($fh);

  my $repo = Repository->new();
  #$repo->setLogger($logger);
  $repo->init($EM_SQL_SCRIPT_ROOT);
  my $h ;
  my @comps = $repo->getComponentsOrdered();
  foreach $h (@comps)
  {
    infoln "parsing component ".$h->getName()."\n";
    $h->parse();
    if ($NO_CONDITION == 0) {
      setComponentConditions($h);
    }
  }  


  print $fh "$EM_SYS_CREDENTIALS \n";
  print $fh "set echo on \n";
  print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_error_switch.sql\n";
  print $fh "set echo $EM_ECHO_SQL \n";
  print $fh "set verify $EM_ECHO_SQL \n";
  print $fh "set feedback $EM_ECHO_SQL \n";
  print $fh "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print $fh "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  print $fh "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print $fh "DEFINE EM_REPOS_PWD = $EM_REPOS_PWD \n";
  print $fh "DEFINE ORACLE_HOME = $ORACLE_HOME \n";
  print $fh "DEFINE EM_PATH_SEP = $EM_PATH_SEP \n";
  
  #replace this with new RepManager code.
  #print $fh "\@$EM_SQL_SCRIPT_ROOT/empatch.sql \n";
      
  my $result_set = executeQuery("select component_name, component_mode, version from $EM_REPOS_USER.MGMT_VERSIONS where version<>'0'");
  my %components ;
  my $row ;
  foreach $row (@$result_set)
  {
    my $hash = {} ;
    $hash->{'name'} = lc @$row[0] ;
    $hash->{'mode'} = @$row[1] ;
    $hash->{'version'} = @$row[2] ;
    $components{$hash->{'name'}} = $hash ;
  }
  
  $result_set = executeQuery
    (
      "select tablespace_name, table_name from all_tables ".
      "where owner ='$EM_REPOS_USER' ".
      "and table_name in ( 'MGMT_TARGETS' , 'MGMT_JOB_PARAMETER' ) ".
      "order by table_name asc"
    );
  
  foreach $row (@$result_set)
  {
    if(@$row[1] eq 'MGMT_TARGETS')
    {
      $EM_DEFAULT_TABLESPACE = @$row[0] ;
    }elsif(@$row[1] eq 'MGMT_JOB_PARAMETER')
    { 
      $EM_ECM_TABLESPACE = @$row[0] ;
    }
  }  
  
  my $core_mode = $components{'core'}->{'mode'} ;
  
  # check whether or not upgrade need to do anything first
  my $should_do_schema = 0;
  foreach $h (@comps)
  {
    if (exists $components{lc $h->getName()})
    {
      my $ver = $components{lc $h->getName()}->{'version'} ;
      if($h->isEqual($ver))
      {
        infoln "component ".$h->getName()." is already at ".$h->getVersion()."\n";
      }else
      {
        $should_do_schema = 1;
      }
    } else
    {
      $should_do_schema = 1;
    }
  }

  if ($should_do_schema eq 0)
  {
    infoln "there is not need to do schema upgrade since all components are up to version\n";
    print $fh "exit;\n";
    close $fh;
    return 0;
  }

  print $fh "DEFINE EM_REPOS_MODE = $core_mode\n" ;
  print $fh "DEFINE EM_TABLESPACE_NAME = $EM_DEFAULT_TABLESPACE\n";
  print $fh "DEFINE EM_ECM_DEPOT_TABLESPACE = $EM_ECM_TABLESPACE\n";
  print $fh "DEFINE EM_ECM_CSA_TABLESPACE_NAME = $EM_ECM_CSA_TABLESPACE \n";
  print $fh "DEFINE EM_ECM_CSA_DATAFILE_NAME = $EM_ECM_CSA_DATAFILE_NAME \n";
  print $fh "DEFINE EM_ECM_CSA_DATAFILE_SIZE = $EM_ECM_CSA_DATAFILE_INIT_SIZE \n";
  print $fh "DEFINE EM_ECM_CSA_DATAFILE_EXT_SIZE = $EM_ECM_CSA_DATAFILE_EXTEND_SIZE \n";
  print $fh "@&EM_SQL_ROOT/core/latest/admin/admin_grants_repos_user.sql \n";

  print $fh "ALTER SESSION SET CURRENT_SCHEMA=$EM_REPOS_USER;\n";
  print $fh "@&ORACLE_HOME/sysman/emdrep/config/pre_upgrade.sql\n";
  print $fh "@&EM_SQL_ROOT/core/latest/admin/admin_remove_dbms_jobs.sql\n";
 
  my $done_schema = 0;  
  foreach $h (@comps)
  {
    infoln "has_upgrade_scripts:".$h->has_upgrade_scripts()."\n";

    if(exists $components{lc $h->getName()})
    {
      my $ver = $components{lc $h->getName()}->{'version'} ;
      if($h->isEqual($ver))
      {
        infoln "component ".$h->getName()." is already at ".$h->getVersion()."\n";
        infoln "skipping ".$h->getName()." upgrade\n";
      }else
      {
        $done_schema = 1;
        infoln "executing ".$h->getName()." schema_upgrade scripts from version $ver\n";
        $h->schema_upgrade($session, $ver);
        infoln "executing ".$h->getName()." recreation scripts\n";
        $h->recreate($session);
      }
    }else
    {
      $done_schema = 1;
      infoln "component ".$h->getName()." does not exist in the current schema.  create it.\n";
      $h->create($session);  
    }
  }
  
  print $fh "@&EM_SQL_ROOT/core/latest/admin/admin_recompile_invalid.sql $EM_REPOS_USER\n";
  
  foreach $h (@comps)
  {
    if(exists $components{lc $h->getName()})
    {
      my $ver = $components{lc $h->getName()}->{'version'} ;
      if($h->isEqual($ver))
      {
        infoln "component ".$h->getName()." is already at ".$h->getVersion()."\n";
        infoln "skipping ".$h->getName()." data upgrade\n";
      }else
      {
        infoln "executing ".$h->getName()." pre data upgrade scripts from versio
n $ver\n";
        $h->pre_data_upgrade($session, $ver);
        infoln "executing ".$h->getName()." data upgrade scripts from version $ver\n";
        $h->data_upgrade($session, $ver);
        $h->post_data_upgrade($session);
        print $fh "@&EM_SQL_ROOT/core/latest/admin/admin_recompile_invalid.sql $EM_REPOS_USER\n";
      }
    }else
    {
      infoln "running post_creation process for component ".$h->getName()."\n";
      $h->post_create($session);
      print $fh "@&EM_SQL_ROOT/core/latest/admin/admin_recompile_invalid.sql $EM_REPOS_USER\n";
      $h->outofbox($session);
    }
    my $cname = uc $h->getName();
    my $newver = $h->getVersion();
    print $fh "EXECUTE EMD_MAINTENANCE.SET_VERSION('$cname', '$newver', '$newver', '$EM_REPOS_MODE');\n";
  }        

  # update ECM metadata meterialized view(s)
  print $fh "EXECUTE EMD_MAINTENANCE.SET_VERSION('_UPGRADE_','0','0','SYSTEM',99);\n"; 
  print $fh "EXECUTE ECM_UTIL.UPDATE_ECM_METADATA;\n";

  print $fh "\@&EM_SQL_ROOT/core/latest/admin/admin_recompile_invalid.sql $EM_REPOS_USER\n";  
  print $fh "\@&EM_SQL_ROOT/core/latest/admin/admin_mgmt_grants.sql $EM_REPOS_USER\n";
  print $fh "ALTER SESSION SET CURRENT_SCHEMA=SYS;\n";  
  
  print $fh "\@&EM_SQL_ROOT/core/latest/admin/admin_analyze_schema.sql \n";
  if ($EM_REPOS_MODE eq "CENTRAL")
  {
    print $fh "set echo on \n";
    print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_error_switch.sql\n";
    print $fh "connect $EM_REPOS_CREDENTIALS \n";
    print $fh "set echo on \n";
    print $fh "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_error_switch.sql\n";
    print $fh "\@&EM_SQL_ROOT/core/latest/admin/admin_remove_dbms_jobs.sql \n";
    print $fh "\@&EM_SQL_ROOT/core/latest/admin/admin_submit_dbms_jobs.sql \n"; 
  }
  print $fh "exit;\n";
  close $fh;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    #load dlf files into repository
    if(!defined $DRY_RUN || $DRY_RUN ne 'true')
    {
      &execTransX;
    }
    &execMetadata;
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub upgradeEMSchema()
{
  # Create a temp file..
  info "Upgrading EM Schema ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print SQL_FILE "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  print SQL_FILE "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print SQL_FILE "DEFINE EM_REPOS_PWD = $EM_REPOS_PWD \n";
  print SQL_FILE "DEFINE ORACLE_HOME = $ORACLE_HOME \n";
  print SQL_FILE "DEFINE EM_PATH_SEP = $EM_PATH_SEP \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/empatch.sql \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_analyze_schema.sql \n";
  if ($EM_REPOS_MODE eq "CENTRAL")
  {
    print SQL_FILE "connect $EM_REPOS_CREDENTIALS \n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_remove_dbms_jobs.sql \n";
    print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_submit_dbms_jobs.sql \n"; 
  }
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    #load dlf files into repository
    &execTransX;
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub listUpgradeErrors()
{
  my $errFound = 0;
  my $erroron = 1;
  my $lineNum = 0;
  my $lineRead;

  # Check the output file for errors
  open(OUTPUT_FILE, "$EM_OUTPUT_FILENAME");
  open(ERROR_FILE, ">$EM_ERROR_FILENAME");

  while (<OUTPUT_FILE>)
  {
    $lineRead = $_;
    $lineNum = $lineNum + 1;
    if (/rem error switch/)
    {
        if ($erroron eq 1)
        {
          $erroron = 0;
        } else {
          $erroron = 1;
        }
    }

    # Check for ORA- or Warning: in lines that dont have Rem or --
    if ( (/^ORA-[0-9]*:/) || ($erroron eq 1 && /^Warning: /) || (/^SP2-/) )
    {
      # Ignore the following errors
      if ( (/^\s*[rR][eE][mM]/) || #Those starting with SQL remarks(case insensitive rem).
           (/^\s*--/) #Those starting with PLSQL style comments.
         )
      {
        # Discount these errors
      }
      else
      {
        # Report the others
        print ERROR_FILE "$lineNum: $lineRead";
        $errFound = 1;
      }
    }
  }
  close ERROR_FILE;
  close OUTPUT_FILE;

  return $errFound;
}

### Downgrade routines.
sub downgradeEMSchema()
{
  # Create a temp file..
  info "Upgrading EM Schema ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print SQL_FILE "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/eme101.sql \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

### Reload routines.
sub reloadEMSchema()
{
  # Create a temp file..
  info "Reloading EM Schema ... ";

  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_SYS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print SQL_FILE "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/emrelod.sql \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}


### Export routines.
sub exportEMRepository()
{
  my $exp_repos_creds = $EM_REPOS_CREDENTIALS;
  my $rc = 0;
  # Create a temp file..
  (my $exparms_fh, my $exp_params_filename) =  create_temp_file(".lst");

  info "Exporting EM repository ... ";
  trace "File - $exp_params_filename.";

  # print EXP_FILE "STATISTICS=NONE \n";
  # Generate the export parameters file
  open(EXP_FILE, "> $exp_params_filename");
  print EXP_FILE "OWNER=$EM_REPOS_USER \n";
  print EXP_FILE "FILE=$EM_EXPORT_DIR/emrepos.dmp \n";
  print EXP_FILE "GRANTS=yes \n";
  print EXP_FILE "TRIGGERS=yes \n";
  print EXP_FILE "INDEXES=yes \n";
  print EXP_FILE "ROWS=yes \n";
  print EXP_FILE "DIRECT=no \n";
  print EXP_FILE "CONSISTENT=y \n";
  print EXP_FILE "STATISTICS=COMPUTE \n";
  close EXP_FILE;

  # Replace = with \= so that exp command will accept repos credentials as one token
  $exp_repos_creds =~ s/=/\\=/g;

  # trace "Repos user creds (modified) = $exp_repos_creds \n";

  $rc = 0xffff & system("$EXPORT \"$exp_repos_creds\" PARFILE=$exp_params_filename 2>> $EM_OUTPUT_FILENAME");

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  unlink $exp_params_filename;
  return $rc;
}


### Import routines.
sub preImportActions()
{
  # Create a temp file..
  info "Executing pre import actions EM Schema ... ";

  # Create a public MGMT_USER role
  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_REPOS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_EXIT \n";
  print SQL_FILE "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print SQL_FILE "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  print SQL_FILE "DEFINE EM_TABLESPACE_NAME = $EM_DEFAULT_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_TEMP_TABLESPACE_NAME = $EM_TEMP_TABLESPACE \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_pre_import.sql \n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}

sub importEMRepository()
{
  my $imp_repos_creds = $EM_REPOS_CREDENTIALS;
  my $rc = 0;
  # Create a temp file..
  (my $imparms_fh, my $imp_params_filename) =  create_temp_file(".lst");

  info "Importing EM repository ... ";
  # print IMP_FILE "TABLES=(*)\n";
  # Generate the import parameters file
  open(IMP_FILE, "> $imp_params_filename");
  print IMP_FILE "FILE=$EM_IMPORT_DIR/emrepos.dmp \n";
  print IMP_FILE "FROMUSER=$EM_REPOS_USER \n";
  print IMP_FILE "TOUSER=$EM_REPOS_USER \n";
  print IMP_FILE "GRANTS=y \n";
  print IMP_FILE "INDEXES=y \n";
  print IMP_FILE "IGNORE=y \n";
  print IMP_FILE "ROWS=y \n";
  print IMP_FILE "COMPILE=n \n";
  print IMP_FILE "SHOW=n \n";
  close IMP_FILE;

  # Replace = with \= so that exp command will accept that as one token
  $imp_repos_creds =~ s/=/\\=/g;

  # trace "Repos user creds (modified) = $imp_repos_creds \n";

  $rc = 0xffff & system("$IMPORT \"$imp_repos_creds\" PARFILE=$imp_params_filename 2>> $EM_OUTPUT_FILENAME");

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  unlink $imp_params_filename;
  return $rc;
}

sub postImportActions()
{
  # Create a temp file..
  info "Executing post import actions EM Schema ... ";

  # Recompile packages
  # Create MGMT_VIEW user and grant select on mgmt$ views
  # Create EM users
  # Enable VPD policy
  # Start notification AQ
  # Start DBMS jobs
  # Reset the sequences
  open(SQL_FILE, "|$SQLPLUS >> $EM_OUTPUT_FILENAME");
  print SQL_FILE "$EM_REPOS_CREDENTIALS \n";
  print SQL_FILE "set echo $EM_ECHO_SQL \n";
  print SQL_FILE "set verify $EM_ECHO_SQL \n";
  print SQL_FILE "set feedback $EM_ECHO_SQL \n";
  print SQL_FILE "$EM_SQL_ERR_CONT \n";
  print SQL_FILE "DEFINE EM_SQL_ROOT = $EM_SQL_SCRIPT_ROOT \n";
  print SQL_FILE "DEFINE ECHO_SQL = $EM_ECHO_SQL \n";
  print SQL_FILE "DEFINE EM_REPOS_USER = $EM_REPOS_USER \n";
  print SQL_FILE "DEFINE EM_TABLESPACE_NAME = $EM_DEFAULT_TABLESPACE \n";
  print SQL_FILE "DEFINE EM_TEMP_TABLESPACE_NAME = $EM_TEMP_TABLESPACE \n";
  print SQL_FILE "\@$EM_SQL_SCRIPT_ROOT/core/latest/admin/admin_post_import.sql \n";
  print SQL_FILE "commit;\n";
  print SQL_FILE "exit;\n";
  close SQL_FILE;

  my $rc = 0xffff & $? ;
  $rc >>= 8;

  trace "Return code = $rc";
  if ($rc eq 0)
  {
    infoln "Done.";
  }
  else
  {
    infoln "Failed.";
  }

  return $rc;
}


##########################checkfor OSAuthentication##################

sub checkOSAuthentication
{
         use Sys::Hostname;
         my $host = hostname;
         my $r1 = rindex($EM_REPOS_CONNSTRING,"Port");
         my $r2 = rindex($EM_REPOS_CONNSTRING,"Host=");
         my $len = $r1-$r2-7;
         my $lhost = substr($EM_REPOS_CONNSTRING,$r2+5,$len);
        if($lhost eq $host)
        {
        if($ENV{'ORACLE_SID'} eq "")
        {
                info "Please set the environment variable ORACLE_SID \n";
                exit 98;
        }
	 else
        {
        open (SQL_FILE, "|$ORACLE_HOME/bin/sqlplus -L / as sysdba ");
        close SQL_FILE;
	 my $rc = 0xffff & $? ;

  	$rc >>= 8;
  	trace "Return code = $rc";
 	 if ($rc eq 0)
  	{
    	 infoln "Done.";
  	}
  	else
  	{
    	 infoln "Failed.";
  	}

  	return $rc;
        }
    }
	 else
        {
        info "Could not connect as OS Authenticated User. Not a Local Host,Enter the Sys password \n";
        exit 98;
        }
}


# ######################### End of Program ###########################

