#!/usr/bin/perl

use File::Spec; 
use File::Path;
use Term::ReadKey;

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

$args = 0 ;
$omsHome = $ARGV[$args];
#print "\noraclehome $omsHome";
$location = $ARGV[$args+1];
#print "\nlocation  $location ";
$cfgFile = File::Spec->catfile($omsHome,"sysman","config","emInstanceMapping.properties");
	if(-e $cfgFile){
		#getting the instance mapping file from the oraclehome
		open(DAT, $cfgFile) || die("Could not open file $propFile! Check if it has read access 
to the current user");
		  @fileContent=<DAT>;
		close(DAT);
		$string_to_find = "EMGC_OMS";
		
		foreach $data (@fileContent)
		{
			chomp($data);
			$data=~tr/\015//d;
			($key,$value)=split(/\=/,$data);
			if ($key =~ m/$string_to_find/g)
			{
				$value =~ s/\\:/:/g;  #s/$find/$replace/g
				$propFile=File::Spec->catfile($value);
			}	
		}
	}
if(-e $propFile){
#getting the required properties from the emgc properties file
	open(DAT, $propFile) || 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 "AS_HOST"){
				$asHost = substr($data, $length+1);
			}
			elsif($key eq "AS_HTTPS_PORT"){
				$asPort = substr($data, $length+1);
			}
		}
#print "$asHost    $asPort \n";
$wls_url="t3s://$asHost:$asPort";
print "The wls url is $wls_url\n";
#password= "Please enter weblogic admin server password : " 

print "\nPlease enter weblogic admin server username : " ;
chop($username=<STDIN>);
$ENV{'username'} = $username;

print "\nPlease enter weblogic admin server password : ";
#chop($sysmanPwd=<STDIN>);
ReadMode 'noecho';
$sysmanPwd = ReadLine 0;
chomp $sysmanPwd;
ReadMode 'normal';
$ENV{'password'} = $sysmanPwd;
print "\n";

$wlst_pro = $ENV{'WLST_PROPERTIES'};
$ENV{'WLST_PROPERTIES'}="-Dweblogic.security.TrustKeyStore=DemoTrust $wlst_pro";
$cmdFile = File::Spec->catfile($omsHome,"oracle_common","common","bin","wlst.sh");
if ($platform =~ /win/){
	$cmdFile = File::Spec->catfile($omsHome,"oracle_common","common","bin","wlst.cmd");
}
#print "The cmdfile is $cmdFile\n";
$pyFile = File::Spec->catfile($omsHome,"OMSPatcher","wlskeys","storeKey.py");
#print "The pyFile is $pyFile\n";
$cfgFile = File::Spec->catfile($location,"config");
print "The cfgFile is $cfgFile\n";
$keyFile = File::Spec->catfile($location,"key");
print "The keyFile is $keyFile\n";

$retVal = -1;

$retVal = system($cmdFile,$pyFile,$wls_url,$cfgFile,$keyFile);

#print "'createkeys' succeeded.";
}
exit $retVal;
