#!/usr/local/bin/perl
# 
# $Header: opatchauto/oms/CloneHomeForNzdt.pl /st_opatchauto_pt-em13.5mos/2 2021/05/31 06:21:54 sallam Exp $
#
# CloneHomeForNzdt.pl
# 
# Copyright (c) 2020, 2021, Oracle and/or its affiliates. 
#
#    NAME
#      CloneHomeForNzdt.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)
#    sallam      10/13/20 - Creation
# 

use File::Spec; 
use File::Path;
use File::Basename;
use File::Find;

sub checkCloneExist
{
	my $home = shift;
	$cloneDetailsFile = File::Spec->catfile($home,".omspatcher_storage","CloneHome.properties");
	if(-e $cloneDetailsFile){
		#CLONED_HOME_PATH=/scratch/emnzdt_134/ClonedHome_2021-01-05_21-46-19
		open(DAT, $cloneDetailsFile) || die("Could not open file $propFile! Check if is exists and has read access to the current user");
			@fileContent=<DAT>;
		close(DAT);
		foreach $data (@fileContent)
		{
			chomp($data);
			$data=~tr/\015//d;
			$length = index($data, '=');
			$key = substr($data, 0 , $length);
			if($key eq "CLONED_HOME_PATH"){
				$cloneHomeLoc = substr($data, $length+1);
				if(-e $cloneHomeLoc){
					print "The home $home is already cloned, So skipping the clone\n";
					#print  "The home $home is not a valid home, So skipping the clone\n";
					exit 1;	
				}					
			}
		}
	}
}
sub checkValidHome
{
	my $home = shift;
	#/sysman/config/emInstanceMapping.properties
	$cfgFile = File::Spec->catfile($home,"sysman","config","emInstanceMapping.properties");
	if(-e $cfgFile){
		#print MYWFILE "The home $home is a valid home\n";
		print  "The home $home is a valid home\n";
	}
	else{
		#print MYWFILE "The home $home is not a valid home\n";
		print  "The home $home is not a valid home\n";
		exit 1;
	}	
}

sub checkSpace
{
	$mwHome = shift;
	my $mwSize;        
	my $parentDir = dirname($mwHome);
	find(sub { $mwSize += -s if -f }, $mwHome);
	my $freespace = `df -h $parentDir | grep '$parentDir' | awk '{print \$3}'`;
#confvert freespace into int
	$freespace=substr($freespace,0,length($freespace)-2);
	my $totalFreeBytes= int($freespace)*1024*1024*1024;
	print "Total size for $mwHome is :$mwSize and parent $parentDir having freespace \t $freespace or ($totalFreeBytes) bytes\n" ;

	if($totalFreeBytes >= 2*$mwSize){
		print "Space available for cloning\n";
	}
	else{
		print "No space available for cloning\n";
		exit 1;
	}
}

sub copyPatchCmd
{
	my $copyCmd = "cp /net/den01nrs.us.oracle.com/scratch/nzdt_134/patches/PatchCmds.pm  $omsHome/bin/PatchCmds.pm";
	print "The command executed is $copyCmd\n";
	$retVal = `$copyCmd`;
	print  "$retVal return value is : $?\n"; 
	$exitCode = $?;
	if($exitCode != 0){
		print "\nThe copy of the PatchCmds : ".getCurrentTime()." Rectify the error and try again\n";
		exit $exitCode;
	}
}

sub cloneOmsHome
{
	print "Running the create clone image\n";
	#$commonHome/bin/copyBinary.sh -javaHome $agentHomeLoc/oracle_common/jdk/ -archiveLoc $srcStageLocation/$srcbackupdirName/oms_clone.jar -sourceOracleHomeLoc $mwHome -silent true -invPtrLoc $invPtrLoc 
	$copySh = File::Spec->catfile($omsHome,"oracle_common","bin","copyBinary.sh");
	$jdk = File::Spec->catfile($omsHome,"oracle_common","jdk");
	$archiveLoc = File::Spec->catfile(dirname($omsHome),"cloneDir","oms_clone.jar");
	
	if (-e $archiveLoc) {
		print "*********deleting $archiveLoc \n";
		$file = File::Spec->catfile(dirname($omsHome),"cloneDir");
		rmtree($file);					
	}
	$copyCmd = "$copySh -javaHome $jdk -archiveLoc $archiveLoc -sourceOracleHomeLoc $omsHome -silent true -invPtrLoc $omsHome/oraInst.loc ";
	print "The command executed is $copyCmd\n";
	#print MYWFILE "The command executed is $cmd\n";
	$retVal = `$copyCmd`;
	print  "$retVal return value is : $?\n"; 
	$exitCode = $?;
	if($exitCode != 0){
		print "\nThe Clone image of oms home failed : ".getCurrentTime()." Rectify the error and try again\n";
		exit $exitCode;
	}

	print "\nSuccessfully executed the command to create the clone image\n ";

	print "Running the clone command \n";
	#$agentHomeLoc/oracle_common/jdk/bin/java -jar $srcStageLocation/$srcbackupdirName/oms.jar -targetOracleHomeLoc $mwHome -invPtrLoc $agentHomeLoc/oraInst.loc -javaHome $agentHomeLoc/oracle_common/jdk					
	
	$javaLoc = File::Spec->catfile($jdk,"bin","java");
	$cloneOmsHome = File::Spec->catfile(dirname($omsHome),"ClonedHome_".getCurrentTime());

	$pasteCmd = "$javaLoc -jar $archiveLoc -targetOracleHomeLoc $cloneOmsHome -invPtrLoc $omsHome/oraInst.loc -javaHome $jdk";
	print "The command executed is $pasteCmd\n";
	#print MYWFILE "The command executed is $cmd\n";
	$retVal = `$pasteCmd`;
	print  "$retVal return value is : $?\n"; 
	$exitCode = $?;
	if($exitCode != 0){
		print "\nThe Clone of oms home failed : ".getCurrentTime()." Rectify the error and try again\n";
		exit $exitCode;
	}
	print "\nSuccessfully executed the command to create the clone home\n ";
	
	$file = File::Spec->catfile(dirname($omsHome),"cloneDir");
	rmtree($file);					
}

sub getCurrentTime{
	($sec,$min,$hour,$mday,$mon,$year)=localtime(time);
	$seperator = "-";
	$year = $year+1900;
	$mon = $mon+1;
	if($mon < 10){
	 $mon = "0$mon";}
	if($mday < 10){
	 $mday = "0$mday";}
	if($hour < 10){
	 $hour = "0$hour";}
	if($min < 10){
	 $min = "0$min";}
	if($sec < 10){
	 $sec = "0$sec";}
	 return $year.$seperator.$mon.$seperator.$mday."_".$hour.$seperator.$min.$seperator.$sec;
}

sub saveCloneDetails
{
	$cloneDetailsFile = File::Spec->catfile($omsHome,".omspatcher_storage","CloneHome.properties");

	if(-e $cloneDetailsFile){
		#print MYWFILE "The home $home is already cloned, So skipping the clone\n";
		print  "The clone home already exist, So deleting the file $cloneDetailsFile\n";
		unlink($cloneDetailsFile);
	}
	open (MYWFILE, ">>$cloneDetailsFile");
	print MYWFILE "CLONED_HOME_PATH=$cloneOmsHome\n";
        print MYWFILE "IS_DOWNTIME_EXECUTED=false\n";
        print MYWFILE "IS_ABORTABLE=true";
	close (MYWFILE);

        $preDowntimeFile = File::Spec->catfile($omsHome,"preDowntime");
        if(-e $preDowntimeFile){
                unlink($preDowntimeFile);
	}
        open (MYWFILE, ">>$preDowntimeFile");
        print MYWFILE "CLONED_HOME_PATH=$cloneOmsHome\n";
        close (MYWFILE);
}
$omsHome = $ARGV[0];
$cloneOmsHome = "";
#parseArgs();

#Check if the home is already cloned
checkCloneExist($omsHome);
# checkValidHome orginal
checkValidHome($omsHome);
#need to copy the patchCmd
#copyPatchCmd();
#checkSpace
#checkSpace($omsHome);
# clone home
cloneOmsHome();
# checkvalidHome clone
checkValidHome($cloneOmsHome);
#save clone home details
saveCloneDetails();
