# $Header: runSQLScript.pl 04-dec-2005.13:34:30 rdabbott Exp $
#
# runSQLScript.pl
# 
# Copyright (c) 2002, 2005, Oracle. All rights reserved.  
#
#    NAME
#      runSQLScript.pl - run a sql script
#
#    DESCRIPTION
#      runs a SQL script 
#
#    NOTES
#      Assumes the stdin of perl is the stdin meant for sqlplus
#      The stdout of sqlplus will become the stdout of perl
#
#    MODIFIED   (MM/DD/YY)
#    rdabbott    12/04/05 - XbranchMerge rdabbott_bug-4387490 from main 
#    rdabbott    12/01/05 - exit with sqlplus's exit code 
#    rdabbott    11/11/05 - not use nolog tweak 
#    rdabbott    11/04/05 - fix 4387490: sql script exits too soon on windows 
#    ashugupt    08/22/05 - Fix 4313412 
#    sbadrina    09/09/04 - change to not use /NOLOG for use in emcli, keep it 
#                           default for use in jobs 
#    xxu         06/25/02 - remove /usr/local/bin/perl
#    rdabbott    06/11/02 - fix oracle home
#    rdabbott    06/10/02 - rdabbott_sql_job2
#    rdabbott    06/10/02 - Creation
# 



# The first two param are the oracle home and sid, the rest are 
# to be passed to SQL Plus directly
$ENV{ORACLE_HOME}       = "$ARGV[0]";
$ENV{ORACLE_SID}        = "$ARGV[1]";
my $CMPARG= "$ARGV[2]";
shift;
shift;

#$ENV{LD_LIBRARY_PATH}   = "$ENV{ORACLE_HOME}/lib:$ENV{LD_LIBRARY_PATH}";
#$ENV{SHLIB_PATH}        = "$ENV{ORACLE_HOME}/lib:$ENV{SHLIB_PATH}";
#$ENV{LIBPATH}           = "$ENV{ORACLE_HOME}/lib:$ENV{LIBPATH}";
#$ENV{PATH}              = "$ENV{ORACLE_HOME}/bin:$ENV{PATH}";

$ENV{LD_LIBRARY_PATH}   = "$ENV{ORACLE_HOME}/lib";
$ENV{SHLIB_PATH}        = "$ENV{ORACLE_HOME}/lib";
$ENV{LIBPATH}           = "$ENV{ORACLE_HOME}/lib";
$ENV{PATH}              = "$ENV{ORACLE_HOME}/bin";

$ENV{ORA_NLS} = "";
$ENV{ORA_NLS32} = "";
$ENV{ORA_NLS33} = "";

my $nolog = '/nolog';


# if NOTUSENOLOG flag is not needed, remove this block
if($CMPARG eq 'NOTUSENOLOG')
{
    shift;
    $nolog = '';
}

my $syscode = system("$ENV{ORACLE_HOME}/bin/sqlplus @ARGV $nolog");
#print "\nReturned from system call: $syscode\n";

$syscode = 0xFFFF & $syscode;

if ( $syscode )
{
    # The signal or core dump is in the low byte
    # program code is in the high byte
    my $sig = 0xFF & $syscode;
    my $ret = $syscode >> 8;

    if ( $sig )
    {
        # if there's a signal, return a negative number
        print "\nSignal from SQLPLUS: $sig\n";
        exit (- $sig);
    }
    else
    {
        # return the positive error code from sqlplus
        print "\nError from SQLPLUS: $ret\n";
        exit $ret;
    }
}

exit 0;