#!/usr/bin/perl
# 
# $Header: opatchauto/oms/PrePatchApply.pl /st_opatchauto_em24.1/1 2025/02/10 17:14:05 smkumbar Exp $
#
# PrePatchApply.pl
# 
# Copyright (c) 2024, 2025, 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);

 
