#
# $Header: adexecsql.pl 120.6.12020000.2 2014/04/03 13:46:47 sbandla ship $
#
# *===========================================================================+
# |  Copyright (c) 2005 Oracle Corporation, Redwood Shores, California, USA   |
# |                        All rights reserved                                |
# |                       Applications  Division                              |
# +===========================================================================+
# |
# | FILENAME
# |   adexecsql.pl
# |
# | DESCRIPTION
# |   Execute all sql scripts that update the profiles in an AutoConfig run
# |
# | USAGE
# |   adexecsql.pl sqlfile=<file> <apps_user> <apps_password>
# |
# | PLATFORM
# |   Generic
# |
# | NOTES
# |
# | HISTORY
# |
# +===========================================================================+
# dbdrv: none 

eval 'exec perl -S $0 "$@"'
if $running_under_some_shell;

use Config;

BEGIN {
    require 5.004;
}

BEGIN {
    # build perl library path environment: PERL5LIB
    #
    # verify, update the include path to be  pointing to 
    # the perl distribution in the iAS or COMMON_TOP Apache HOME.
    if (($Config{'osname'} ne "MSWin32") && (! $ENV{'PERL5LIB'})) {
        my $value = "";
        my $envkey = "";
        my @tmpINC = ();
        my $perlPath = "";
        my $pcmd = 'perl';
        my %keyHash;
        foreach (split /:/, $ENV{PATH}) {
            $perlPath = "$_/$pcmd", last if -x "$_/$pcmd";
        }
        my $dir = ""; 
        if ($perlPath =~ /(.*?\/)perl/) {
            $dir = $1;
        }

        if ($dir =~ /Apache/) {
            my $swap_plib = 0;

            # this covers the build case for the 11.5.1 perl
            # distribution in Apache.
            if (-d "${dir}perl/perl5/5.00503") {
                $swap_plib = 1;
            }
            foreach $value (@INC) {
                if ($value =~ /.*?(perl.*)/) {
                    my $plib_home = $1;

                    if ($swap_plib) {
                        $plib_home =~ s/perl\/lib/perl\/perl5/;
                    }
                    push @tmpINC, "${dir}$plib_home";
                }
            }
            @INC = @tmpINC;
            foreach $val (@INC) {
              $val =~ s/^\s*|\s*$//ig;
              $keyHash{$val} = $val;
            }
            @INC = keys(%keyHash);
        }
    }
}

use POSIX qw(strftime);
use ADX::util::Sysutil;

#
# Method to determine the tier
# Returns apps in case of Applications tier and db in case of Database tier
#
sub getTier {
    my $contexttype='APPL_TOP Context';
    if ($contexttype =~ "APPL_TOP") {
        return "apps";
    } elsif ($contexttype =~ "%s_") {
        my $appl ='/u01/oracle/uat/fs1/EBSapps/appl';
        if ($appl !~ "%s_") {
            return "apps";
        }
    }
    return "db";  
}

#
# Set environment variables based on the tier
#
sub setENV {
    my $tier = getTier();
    my $sep;
    if(($Config{'osname'} ne "MSWin32") && ($Config{osname} ne 'Windows_NT')){
        $sep = ":";
    } else {
        $sep = ";";
    }
    my $path;
    my $twotask;
    if($tier =~ "apps") {
        $path = '/u01/oracle/uat/fs1/EBSapps/10.1.2/bin:/u01/oracle/uat/fs1/EBSapps/comn/util/jdk/jre/bin:/usr/bin:/usr/ccs/bin:/usr/sbin:$PATH' . $sep. $ENV{PATH};
        my $fstype = 'patch';
        printf "File System type : $fstype\n";
         if ("$fstype" eq "run")
        {
          $twotask='UAT_BALANCE';
        }
        else
        {
          $twotask='UAT_patch';
        }
        $ENV{ORACLE_HOME} = '/u01/oracle/uat/fs1/EBSapps/10.1.2';
        $ENV{LD_LIBRARY_PATH} = '/u01/oracle/uat/fs1/EBSapps/10.1.2/lib32:/u01/oracle/uat/fs1/EBSapps/10.1.2/lib:/usr/dt/lib:/usr/openwin/lib:/u01/oracle/uat/fs1/EBSapps/10.1.2/jdk/jre/lib/sparc:/u01/oracle/uat/fs1/EBSapps/10.1.2/jdk/jre/lib/sparc/native_threads:/u01/oracle/uat/fs1/EBSapps/appl/sht/12.0.0/lib:/u01/oracle/uat/fs1/EBSapps/10.1.2/jdk/jre/lib/sparc/client';
        $ENV{TNS_ADMIN} = '/u01/oracle/uat/fs1/inst/apps/UAT_sun3app2/ora/10.1.2/network/admin';
    } else {
        $path = '%s_db_path%' . $sep . $ENV{PATH};
        $twotask='UAT';
        $ENV{ORACLE_HOME} = '%s_db_oh%';
        if(($Config{'osname'} ne "MSWin32") && ($Config{osname} ne 'Windows_NT')){
           $ENV{LD_LIBRARY_PATH} = '%s_db_ldlib%';
        } else {
           $ENV{LD_LIBRARY_PATH} = '%s_db_oh%\lib';
        }
        $ENV{TNS_ADMIN} = '%s_db_tnsadmin%';
    }
    $ENV{PATH} = $path;
    if(($Config{'osname'} ne "MSWin32") && ($Config{osname} ne 'Windows_NT')){
        if($tier =~ "apps") {
            $ENV{TWO_TASK} = $twotask;
        } else {
            $ENV{ORACLE_SID} = $twotask;
        } 
    } else {
        if($tier =~ "apps") {
            $ENV{LOCAL} = $twotask;
        } else {
            $ENV{ORACLE_SID} = $twotask;
        } 
    }
    return $twotask;
}

# main 
#
# program entry point  
#
sub main {
    my $time = strftime "%a, %m %b %Y %H:%M:%S %z", localtime;
    my $Progname;
    ($Progname = $0) =~ s,.*[/\\],,;
    $| = 1;
    printf "\n$Progname started at $time\n\n";

    my $appspass;
    my $appsuser;
    my $ctxfile;
    my $sqlfile;
    my $twotask;

    my $arg;
    my $count = @ARGV;
    if($count < 1) {
        print "Invalid number of parameters passed. \n Usage\n";
        print "\tadexecsql.pl sqlfile=<file> \n";
        printf "ERRORCODE = 1 ERRORCODE_END\n";
        exit 1;
    }
    $arg = shift(@ARGV);
    if ($arg =~ /^(-)?(-)?s(qlfile)?=(.*$)/) {
        $sqlfile = $4;
    } else {
        print "Invalid usage. First parameter is of form sqlfile=<file>\n"; 
        print "Usage\n\tadexecsql.pl sqlfile=<file> \n";
        printf "ERRORCODE = 1 ERRORCODE_END\n";
        exit 1;
    }
    chomp($appsuser = <STDIN>);   
    chomp($appspass = <STDIN>);
    $twotask=setENV();

    printf "\nThe environment settings are as follows ...\n\n";
    printf "       ORACLE_HOME : $ENV{ORACLE_HOME}\n";
    if($Config{'osname'} ne "MSWin32") {
        printf "          TWO_TASK : $ENV{TWO_TASK}\n";

        printf "              PATH : $ENV{PATH}\n";
        printf "         TNS_ADMIN : $ENV{TNS_ADMIN}\n";
        printf "   LD_LIBRARY_PATH : $ENV{LD_LIBRARY_PATH}\n\n";
    } else {
        printf "             LOCAL : $ENV{LOCAL}\n";

        printf "              PATH : $ENV{PATH}\n";
        printf "         TNS_ADMIN : $ENV{TNS_ADMIN}\n";
    }
    if(($Config{'osname'} ne "MSWin32") && ($Config{osname} ne 'Windows_NT')){
        printf "SQLPLUS Executable : " . getsqlplus($ENV{PATH}) . "\n\n";
    } else {
        printf "Running SQL script : " . $sqlfile . "\n\n";
    }

    my $err;
    $err=ADX::util::Sysutil->runPipedCmd("sqlplus /nolog \@$sqlfile","$appsuser","$appspass","$twotask");
    if ( $err != 0 ) {
        printf "Error encountered while running $sqlfile \n";
    }
    printf "ERRORCODE = $err ERRORCODE_END\n";
    exit $err;
}

#
# Method to get sqlplus binary location in case ofunix platforms
#
sub getsqlplus {
    my $path = $_[0];
    my @path=split(/:/,$path);
    foreach $dir (@path) {
        $bin="$dir/sqlplus";
        $bin =~ s|/+|/|oig;
        if ( -f $bin ) {
            return $bin;
        }
    }
}

# runSystemCmd
#
# executes the passed command in the different os environments
#
sub runSystemCmd {

    my $cmd = $_[0];
    chomp($cmd);
    my $exitValue = 0;
    if (system($cmd) != 0) {
        $exitValue = $? >> 8;
    }
    return $exitValue;
}

main();
