#!/usr/bin/perl
# 
# $Header: opatchauto/oms/PrePatchApply.pl /st_opatchauto_pt-em13.5mos/1 2024/11/27 21:59:30 smkumbar Exp $
#
# PrePatchApply.pl
# 
# Copyright (c) 2024, Oracle and/or its affiliates. 
#
#    NAME
#      PrePatchApply.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)
#    smkumbar    11/27/24 - PrePatch apply for holistic patching
#    smkumbar    11/27/24 - Creation
#
use File::Spec;
use File::Basename;

sub apply {
    my ($patchAbsPath, $oracleHome, $fh, $datestring,$platform) = @_;
    my $opatchLocation;
    $opatchLocation = File::Spec->catfile($oracleHome,"OPatch","opatch");
    if ($platform =~ /win/){
	$opatchLocation = File::Spec->catfile($oracleHome,"OPatch","opatch.bat");
    }
    my $applyCommand = "$opatchLocation apply $patchAbsPath -silent -oh $oracleHome";
    print $fh "$datestring :: Apply command : $applyCommand\n";
    my $applyOutLog = `$applyCommand`;
    if ($? != 0) {
        print $fh "$datestring :: Error while applying patch : $applyOutLog\n";
        close ($fh);
        die "Could not apply the patch $!\n";
    }
    print $fh "$datestring :: The opatch apply log : $applyOutLog\n";
}


sub getPrePatchId {
    my ($prePatchLocation) = @_;
    unless (-d $prePatchLocation) {
        return -1;
    }
    opendir(my $dh, $prePatchLocation) or return -2;
    my @entries = readdir($dh);
    closedir($dh);
    my @folders = grep { -d File::Spec->catfile($prePatchLocation, $_) && !/^\.\.?$/ } @entries;
    if (@folders == 0) {
        return -3;
    } elsif (@folders != 1) {
        return -4;
    }
    return $folders[0];
}

my $oracleHome = @ARGV[0];
my $patchLocation = @ARGV[1];

$platform = $^O;
$platform=lc($platform);

my $datestring = localtime();
my $logTimeStamp = localtime();
$logTimeStamp =~ s/ /_/g;
$logTimeStamp =~ s/:/_/g;
my $prePatchApplyLog = File::Spec->catfile($oracleHome,"cfgtoollogs","omspatcher","SPB_PATCH","opatch_prepatch_$logTimeStamp.log");
my $prePatchLocation = File::Spec->catfile($patchLocation, "binary_patches", "pre_hp", "generic");


my $prePatchId = getPrePatchId($prePatchLocation);
my $fh;
open ($fh, '>', $prePatchApplyLog);
print $fh "$datestring :: The prepatch id is $prePatchId\n";

if($prePatchId >= 0) {
    my $patchAbsPath = File::Spec->catfile($prePatchLocation, $prePatchId);
    apply($patchAbsPath, $oracleHome, $fh, $datestring,$platform);
}
else {
    print $fh "$datestring :: The prepatch does not exist. Error code: $prePatchId\n";
    close ($fh);
    #exit 1;
}
close ($fh);

 
