#
#  $Header: emcore/scripts/emctl/SecureOMSCmds.pm /st_emcore_10.2.0.4.2db11.2/1 2009/06/23 13:20:09 pchebrol Exp $
#
#
# Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved. 
#
#    NAME
#      SecureOMSCmds.pm - Secure OMS Perl Module
#
#    DESCRIPTION
#
#    NOTES
#
#    MODIFIED   (MM/DD/YY)
#    pchebrol    06/12/09 - PID 3928827 - remove hard coded pwd
#    jashukla    06/02/08 - Bug 7144619 remove internal identifiers
#    pchebrol    06/22/07 - Backport shianand_core_5121288 from main
#    pchebrol    06/21/07 - 
#    rpinnama    05/09/07 - Bug 6019771 : Fix secure with big-ip
#    shianand    12/22/06 - fix bug 5692755
#    shianand    12/22/06 - fix bug 5727049
#    shianand    09/25/06 - fix bug 5520464
#    shianand    07/21/06 - Backport shianand_bug-4516559 from main 
#    shianand    01/03/06 - Moving SSO registration to SecureOMSCmds.pm 
#    shianand    01/03/06 - fix bug 4911857 
#    shianand    07/21/06 - Backport shianand_bug-4911857 from main 
#    shianand    01/09/06 - XbranchMerge shianand_bug-4895199 from main 
#    shianand    01/05/06 - Backport shianand_bug-4894781 from main 
#    shianand    12/29/05 - XbranchMerge shianand_bug-4895199 from main 
#    shianand    12/02/05 - Backport shianand_bug-4570579 from main 
#    shianand    11/09/05 - fix the password from command line 
#    shianand    11/07/05 - fix bug 4570537 
#    shianand    11/06/05 - Fix bug 4570579 
#    shianand    11/14/05 - fix bug 4481271 
#    shianand    11/14/05 - fix bug 4360441 
#    shianand    08/08/05 - fix bug 4543785 
#    shianand    08/08/05 - fix bug 4516559 
#    shianand    09/06/05 - fix bug 4591108 
#    kmanicka    08/24/05 - check if emkey is configured
#    rkpandey    08/24/05 - Increased Apache default timeout 
#    shianand    07/23/05 - fix bug 3335221 
#    shianand    07/25/05 - fix bug 4509232 
#    shianand    07/15/05 - shianand_ref_core
#    shianand    03/31/05 - Created
#
#


package SecureOMSCmds;

use IPC::Open2;
use English;
use strict;
use vars '*args';

use EmCommonCmdDriver;
use EmctlCommon;
use EmKeyCmds;
use SecureUtil;

my $ORACLE_HOME       = $ENV{ORACLE_HOME};
my $JAVA_HOME         = $ENV{JAVA_HOME};
my $emUploadHTTPPort  = $ENV{EM_UPLOAD_PORT};
my $emUploadHTTPSPort = $ENV{EM_UPLOAD_HTTPS_PORT};
my $httpServerTimeout = "900";
my $IS_WINDOWS        = "";
my $redirectStderr    = "2>&1";
my $opmnRedirectLog   = "";

my $securelog         = "$ORACLE_HOME/sysman/log/secure.log";
SecureUtil::setLogFile($securelog);

SecureUtil::setDebug($ENV{EM_SECURE_VERBOSE});
my $debug = SecureUtil::getDebug;

my $OSNAME            = $^O;
if( ($OSNAME eq "MSWin32") or ($OSNAME eq "Windows_NT") )
{
 $IS_WINDOWS="TRUE";
 $opmnRedirectLog = "$devNull 2>&1";
}
else
{
 $IS_WINDOWS="FALSE";
 $opmnRedirectLog   = "$securelog 2>&1";
}

# SSO debug parameters
my $debugFlag = "";

# SSO host parameters
my $hostname = &EmctlCommon::getLocalHostName();
my $port     = (SecureOMSCmds::getOMSPorts())->[0];
my $ohm      = $ORACLE_HOME;
my $domain   = "";

# SSO config file
my $configfile = "$ohm/Apache/Apache/conf/httpd.conf";
my $propfile   = "$ohm/sysman/config/emoms.properties";
my $tempfile   = "temp.ssosetup";


# SSO server parameters - taken from command line
my $serverhost    = "";
my $serverport    = "";  # db port
my $serversid     = "";
my $serverpwd     = "";
my $serverwebport = "";
my $dasurl        = "";
my $serverschema  = "orasso"; # default value
my $user          = "";

sub new
{
  my $classname = shift;
  my $self = { };
  bless ($self, $classname);
  return $self;
}

sub doIT
{
  my $classname = shift;
  my $rargs     = shift;
  my $result    = $EMCTL_UNK_CMD; #Unknown command.

  my $argCount  = @$rargs;
  if ($argCount >= 2  && $rargs->[0] eq "secure")
  {
    if($rargs->[1] eq "oms")
    {
       secure($rargs);
       $result = $EMCTL_DONE;
    }
    elsif($rargs->[1] eq "sync")
    {
       secureSync();
       $result = $EMCTL_DONE;
    }
    elsif ($rargs->[1] eq "setpwd")
    {
      secureSetPwd ($rargs);
      $result = $EMCTL_DONE;
    }
    elsif ($rargs->[1] eq "lock" || $rargs->[1] eq "unlock")
    {
      secureLock($rargs);
      $result = $EMCTL_DONE;
    }
    elsif ($rargs->[1] eq "genwallet")
    {
      local (*args) = $rargs;
      shift(@args);
      shift(@args);
      my $agentHostName     = $args[0];
      my $obfWalletPassword = $args[1];
      my $retVal;

      # NOTE : Use a different secure log. Otherwise, the emctl secure genwallet callout
      #        from OMS will fail with "The file is being accesses by another process" 
      #        If this is not done, both agent secure process and OMS
      #        try to redirect their output to the same log file
      #        Also, two agent trying to secure at the same time (multiple secure genwallet callouts)
      #        also will have problem if the same securelog file is used.
      my $securelog            = "$ORACLE_HOME/sysman/wallets/agent.$agentHostName/secure.log";
      SecureUtil::setLogFile($securelog);
      my $emConsoleMode        = "CENTRAL";
      my $walletType           = "agent";
      my $thisDNSHost          = $agentHostName;
      my $obfOMSWalletPassword = $obfWalletPassword;
      my $rootKeyDir           = "rep";
      my $certName             = $agentHostName;
      my $rootKeyPassword      = "";
      my $obfEMRootPassword    = "";

      $retVal = genWallet ($securelog, $emConsoleMode, $thisDNSHost,  $obfOMSWalletPassword,
                           $rootKeyDir,  $certName,  $walletType, $obfEMRootPassword);
      SecureUtil::setLogFile("$ORACLE_HOME/sysman/log/secure.log");
      exit $retVal;
    }
    else
    {
       $result = $EMCTL_UNK_CMD;
    }
  }
  else
  {
    $result = $EMCTL_UNK_CMD;
  }
  return $result;
} 


sub usage
{
  print "Secure OMS Usage : \n";
  print "emctl secure oms -sysman_pwd <sysman password> -reg_pwd <registration password> [-host <hostname>]\n";
  print "\t[-reset] [-secure_port <secure_port>] [-slb_port <slb port>] [-root_dc <root_dc>] [-root_country <root_country>]\n";
  print "\t[-root_state <root_state>] [-root_loc <root_loc>] [-root_org <root_org>] [-root_unit <root_unit>]\n";
  print "\t[-root_email <root_email>]\n";
  print "emctl secure setpwd [authpasswd] [newpasswd]\n";
  print "emctl secure sync\n";
  print "emctl secure lock\n";
  print "emctl secure unlock\n\n";
}


sub secure
{
  local (*args) = @_;
  shift(@args);
  my $component = @args->[0];
  my $argCount  = scalar(@args); 
  
  my $regPassword   = "";         # agent reg password
  my $rootPassword  = "";         # SYSMAN password
  my $omsSLBHost    = "";         # OMS Host or SLB host in SLB env
  my $omsReset      = "";         # Whether to reset root password
  my $emConsoleMode = "CENTRAL"; # default to central

  my $authPassword  = "";
  my $newPassword   = "";
  my $omsUrl        = "";
  my $thisDNSHost   = "";
  my $agentCertName = "";

  my $root_dc      = "";
  my $root_country = "";
  my $root_state   = "";
  my $root_loc     = "";
  my $root_org     = "";
  my $root_unit    = "";
  my $root_email   = "";
  my $slbSecUploadPort = "";

  if ($component eq "oms")
  {
    # get em root password, registration password(*), [host] and [reset] either 
    # from the args or interactive 
    if ($argCount eq 1)
    {
      my @passwordReads = &EmctlCommon::promptUserPasswds("Enter Enterprise Manager Root Password : ",
                                 "Enter Agent Registration password : ");
      $rootPassword = $passwordReads[0];
      $regPassword  = $passwordReads[1];
    }
    else
    {
      shift (@args);
      $rootPassword  = "";
      $regPassword   = "";
      $omsSLBHost    = "";
      $omsReset      = "";
         
         
     #now process  parameters -sysman_pwd -reg_pwd -host, -reset and -secure_port
     #if -sysman_pwd or -reg_pwd missing, prompt user
     while (scalar(@args) gt 0)
     {
       if ($args[0] eq "-sysman_pwd")
       {
          shift(@args);
          $rootPassword       = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-reg_pwd")
       {
          shift(@args);
          $regPassword       = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-host")
       {
          shift(@args);
          $omsSLBHost       = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-reset")
       {
          $omsReset      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-secure_port")
       {
          shift(@args);
          $emUploadHTTPSPort      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-slb_port")
       {
          shift(@args);
          $slbSecUploadPort  = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-root_dc")
       {
          shift(@args);
          $root_dc      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-root_country")
       {
          shift(@args);
          $root_country      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-root_state")
       {
          shift(@args);
          $root_state      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-root_loc")
       {
          shift(@args);
          $root_loc      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-root_org")
       {
          shift(@args);
          $root_org      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-root_unit")
       {
          shift(@args);
          $root_unit      = $args[0];
          shift(@args);
       }
       elsif ($args[0] eq "-root_email")
       {
          shift(@args);
          $root_email      = $args[0];
          shift(@args);
       }
       else
       {
          exit $EMCTL_UNK_CMD;
       }
     } 
       if ($rootPassword eq "")
       {
         $rootPassword=&EmctlCommon::promptUserPasswd(
                                  "Enter Enterprise Manager Root Password : ");
       }
       if ($regPassword eq "")
       {
         $regPassword=&EmctlCommon::promptUserPasswd(
                                  "Enter Agent Registration password : ");
       }
     }
    $emConsoleMode    = &SecureUtil::getConsoleMode;
    my $portsRef      = getOMSPorts();
    my @tempPorts     = @$portsRef;
    $emUploadHTTPPort = $tempPorts[0];
    
    if ($emConsoleMode eq "")
    {
      SecureUtil::USERINFO ("Cannot determine Console type from oms.properties\n");
    }
    elsif ($emUploadHTTPPort eq "")
    {
      SecureUtil::USERINFO ("Cannot determine console http port from httpd_em.conf\n");
    }
    else
    {
      if ($emConsoleMode eq "STANDALONE")
      {
        SecureUtil::USERINFO ("You must use emctl secure em to secure an iAS or ");
        SecureUtil::USERINFO ("a DBA Studio\n");
        SecureUtil::USERINFO ("Standalone Console.\n");
      }
      else
      { 
        if ($emUploadHTTPSPort eq "")
        {
          if ($tempPorts[1] eq "")
          {
            $emUploadHTTPSPort = "4888";
          }
          else
          {
            $emUploadHTTPSPort = $tempPorts[1]
          } 
        }
        secureCentralOMS($securelog, $emConsoleMode, $emUploadHTTPPort, 
                         $emUploadHTTPSPort, $rootPassword, $regPassword, 
                         $omsSLBHost, $omsReset, $root_dc, $root_country,
                         $root_state, $root_loc, $root_org, $root_unit, $root_email,$slbSecUploadPort); 
      }
    }
  }
  else
  {
    exit $EMCTL_BAD_USAGE;
  }
}

#
# secureSync takes
# 1) Array of arguments
#
sub secureSync
{
  local (*args) = @_;
  shift(@args);
  shift(@args);
  my $javaStr   = "";
  my $classPath = "";
  my $rc;

  $classPath = &SecureUtil::getConsoleClassPath("");

  $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DrepositoryPropertiesFile=$ORACLE_HOME/sysman/config/emoms.properties ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.InstallPassword -auth ".
             ">> $securelog";

  SecureUtil::DEBUG ("Executing ... $javaStr");

  open(SETPWD, "|$javaStr");
  print SETPWD "nopassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;
  if (not $rc eq 2 )
  {
    SecureUtil::USERINFO ("   Done.\n");
  }
  else
  {
    SecureUtil::USERINFO ("   Failed.\n");
  }
  return $rc;
}




#
# secureSetPwd takes
# 1) Array of arguments
#
sub secureSetPwd
{
  local (*args) = @_;
  shift(@args);
  shift(@args);
  my $authPassword = $args[0];
  my $newPassword  = $args[1];
  
  if ($authPassword eq "")
  {
    $authPassword=&EmctlCommon::promptUserPasswd(
                               "Enter Enterprise Manager Root Password : ");
  }

  if ($newPassword eq "")
  {
    $newPassword=&EmctlCommon::promptUserPasswd(
                               "Enter New Agent Registration Password : ");
  }

  my $javaStr = "";
  my $classPath = &SecureUtil::getConsoleClassPath("");
  my $rc;


  #
  # check if the emkey is configured properly in the file system
  #
  SecureUtil::DEBUG ("Checking Em Key... ");
  my $emKeyStatus = EmKeyCmds::verifyEmKey($authPassword,"false");

  if($emKeyStatus eq 0 or $emKeyStatus eq 1 or $emKeyStatus eq 2)
  {
    SecureUtil::DEBUG (" The Em Key is configured properly... ");
    $javaStr = "$JAVA_HOME/bin/java ".
               "-cp $classPath ".
               "-DrepositoryPropertiesFile=$ORACLE_HOME/sysman/config/emoms.properties ".
               "-Ddebug=$debug ".
               "oracle.sysman.eml.sec.rep.InstallPassword -set_pwd ".
               ">> $securelog";

  SecureUtil::DEBUG ("Executing ... $javaStr");

  open(SETPWD, "|$javaStr");
  print SETPWD "$authPassword\n";
  print SETPWD "$newPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;

    if($rc eq 0)
    {
        SecureUtil::USERINFO ("Agent Registration Password reset Succesful.\n");
    }
    elsif($rc eq 2)
    {
        SecureUtil::USERINFO ("Failed to reset Agent Registration Password.\n");
    }
    else
    {
        SecureUtil::USERINFO ("Failed. Invalid sysman password.\n");
    }
  }
  else
  {
    # if the emkey is not configured Properly
    SecureUtil::USERINFO ("Failed to reset Agent Registration Password.\n");
    SecureUtil::USERINFO ("The Em Key is not Configured properly.Run \"emctl status emkey\" for details\n");
    $rc = 2;
  }

  return $rc;
}



#
# secureStatus takes
# 1) Array of arguments
#

sub secureStatus
{
  my $component    = $args[0];
  my $omsUrl       = $args[1];
  my $agentUrl     = "";

  my $httpsPortCmd = "";
  my $httpsPort    = "";
  my $statusAtOMS   = "false";
  my $statusAtAgent = "false";
  my $propFile;
  my $statusArgs;

  my $javaStr      = "";
  my $classPath    = "";
  my $rc;

  my $emAgentMode      = &SecureUtil::getAgentMode();
  my $emHome           = &SecureUtil::getEMHome($emAgentMode);
  my $emdPropFile      = "$emHome/sysman/config/emd.properties";
  my ($protocol,$machine,$port,$ssl);
  my %agentProps;

  if (-e "$ORACLE_HOME/sysman/config/emoms.properties")
  {
    $statusAtOMS = "true";
    $classPath   = &SecureUtil::getConsoleClassPath("");
    $propFile    = "$ORACLE_HOME/sysman/config/emoms.properties";
  }
  else
  {
    $statusAtOMS = "false";
    $classPath   = &SecureUtil::getAgentClassPath;
    $propFile    = "$ORACLE_HOME/sysman/config/emd.properties";
  }

  if ($omsUrl eq "")
  {
    if ($component eq "oms")
    {
      $statusAtAgent = "false";
    }
    elsif ($component eq "agent")
    {
      $statusAtAgent = "true";
      if ($emAgentMode ne "")
      {
        if ($emAgentMode eq "CENTRAL_AGENT")
        {
          %agentProps  = &SecureUtil::parseFile($emdPropFile);
          if (defined($agentProps{"REPOSITORY_URL"}))
          {
             $omsUrl = $agentProps{"REPOSITORY_URL"};
             if ($omsUrl =~ /https/)
             {
               ($protocol,$machine,$port,$ssl) = &SecureUtil::parseURL($agentProps{"emdWalletSrcUrl"});
               my @url = split(/:/, $omsUrl);
               my @upload_dir = split(/\//,$url[2]);
               $omsUrl ="http:$url[1]:$port/$upload_dir[1]/$upload_dir[2]/\n";
               chomp($omsUrl);
             }
          }
        }
      }
      else
      {
        $statusAtAgent = "false";
      }
    }
  }
  else
  {
    if ($component eq "oms")
    {
      $statusAtAgent = "false";
    }
    if ($component eq "agent")
    {
      if ($emAgentMode ne "")
      {
        $statusAtAgent = "true";
      }
      else
      {
        $statusAtAgent = "false";
      }
    }
  }

  if ($statusAtAgent eq "true")
  {
    SecureUtil::USERINFO ("Checking the security status of the Agent at location set in $emdPropFile...");
    %agentProps  = &SecureUtil::parseFile($emdPropFile);
    ($protocol,$machine,$port,$ssl) = &SecureUtil::parseURL($agentProps{"EMD_URL"});
    SecureUtil::USERINFO ("  Done.\n");
    if($ssl eq "Y")
    {
       SecureUtil::USERINFO ("Agent is secure at HTTPS Port $port.\n");
    }
    else
    {
       SecureUtil::USERINFO ("Agent is unsecure at HTTP Port $port.\n");
    }
  }

   SecureUtil::USERINFO ("Checking the security status of the OMS at ");
  if ($omsUrl eq "")
  {
     SecureUtil::USERINFO ("location set in $propFile...");
    if ($statusAtOMS eq "true")
    {
      $statusArgs = "-localOMS";
    }
    else
    {
      $statusArgs = "";
    }
  } 
  else
  {
    SecureUtil::USERINFO ("$omsUrl...");
    $statusArgs = $omsUrl;
  }
  $javaStr = "$JAVA_HOME/bin/java ".
                   "-cp $classPath ".
                   "-DpropertiesFile=$propFile ".
                   "-Ddebug=$debug ".
                   "oracle.sysman.eml.sec.emd.GetSecPort $statusArgs ".
                   ">> $securelog";
  $rc = 0xffff & system($javaStr);
  $rc >>= 8;
  if ( $rc eq 0 )
  {
    SecureUtil::USERINFO ("  Done.\n");
    $httpsPortCmd = "$JAVA_HOME/bin/java ".
                    "-cp $classPath ".
                    "-DpropertiesFile=$propFile ".
                    "-Ddebug=$debug ".
                    "oracle.sysman.eml.sec.emd.GetSecPort $statusArgs";
    $httpsPort = `$httpsPortCmd`;
    $httpsPort =~ s/^\s+|\s+$//;
    SecureUtil::USERINFO ("OMS is secure on HTTPS Port $httpsPort\n");
  }
  else
  {
    if ( $rc eq 2 )
    {
      SecureUtil::USERINFO ("   Done.\n");
      SecureUtil::USERINFO ("OMS is running but has not been secured. No HTTPS Port available.\n");
    }
    else
    {
      SecureUtil::USERINFO ("   Failed.\n");
      SecureUtil::USERINFO ("Could not connect to the OMS.");
    }
  }
  return $rc;
}


#
# secureLock takes
# 1) Array of arguments
#

sub secureLock
{
  local (*args) = @_;
  shift(@args);
  my $lockStatus                         = $args[0];
  my $portsRef                           = getOMSPorts();
  ($emUploadHTTPPort, $emUploadHTTPSPort) = @$portsRef;

  my $emUploadDeny = ($lockStatus eq "lock") ? "all" : "none";

  SecureUtil::setLogFile($securelog);

  my $thisDNSHost       = &EmctlCommon::getLocalHostName();
  my $omsStatusCmd      = "";
  my $rc;
  my $classPath         = &SecureUtil::getConsoleClassPath("");

  $thisDNSHost       =~ s/^\s+|\s+$//;

  my $propFile = "$ORACLE_HOME/sysman/config/emoms.properties";
  my $httpEmConfTemplateFile = "$ORACLE_HOME/sysman/config/httpd_em.conf.template";
  my $httpEmConfFile         = "$ORACLE_HOME/sysman/config/httpd_em.conf";

  my @procStatus = `$ORACLE_HOME/dcm/bin/dcmctl getState -v -d`;
  my $ohsStatus = statusOHS (@procStatus);
  my $execStr = "";
  my $httpdStatus = "false";

  SecureUtil::USERINFO ("Checking the security status of the OMS...");

  $omsStatusCmd = "$JAVA_HOME/bin/java ".
                  "-cp  $classPath ".
                  "-DpropertiesFile=$propFile ".
                  "-Ddebug=$debug ".
                  "oracle.sysman.eml.sec.emd.GetSecPort -localOMS";

  SecureUtil::DEBUG ("Executing .. $omsStatusCmd");

  my $statusOut =`$omsStatusCmd`;

  chop $statusOut;
  if ($statusOut eq "2")
  {
    SecureUtil::USERINFO ("   Failed.\n");
    SecureUtil::USERINFO ("OMS is not Secure. Use emctl secure oms before attempting to lock.\n");
    exit $statusOut;
  }
  elsif ($statusOut eq "1")
  {
    SecureUtil::USERINFO ("   Failed.\n");
    SecureUtil::USERINFO ("Unable to detect an OMS at the location set in $propFile\n");
    exit $statusOut;
  }
  else
  {
    SecureUtil::USERINFO ("   Done.\n");
  }
   
  #
  # if we are already in the right lock or unlock mode dont do anything.
  #
  open(EMCONFH, $httpEmConfFile) || die "Could not open $httpEmConfFile";
  my $vhost = "\*:$emUploadHTTPPort";
  my $curLine;
  my $insideVH = 0;
  while(defined($curLine = <EMCONFH>) && ($insideVH == 0))
  {
    chop $curLine;
    if ($curLine =~ /^.*<VirtualHost\s+\*:$emUploadHTTPPort>/) 
    {
      $insideVH = 1;
    }
  }
  if ($insideVH == 0) 
  {
      SecureUtil::USERINFO ("Parsing error. Virtual Host not found.\n");
      exit -2;
  }
  
  SecureUtil::DEBUG ("VirtualHost found...");

  my $insideUpload = 0;
  while(defined($curLine = <EMCONFH>) && ($insideUpload == 0))
  {
    chop $curLine;
    if ($curLine =~ /^.*<Location\s+\/em\/upload>/)
    {
      $insideUpload = 1;
    }
  }
  if ($insideUpload == 0)
  {
    SecureUtil::USERINFO ("Parsing error. Location of upload section not found.\n");
    exit -3;
  }

  SecureUtil::DEBUG ("Location found..");
  
  my $denyValue = "";
  while(defined($curLine = <EMCONFH>) && ($denyValue eq ""))
  {
    chop $curLine;
    if ($curLine =~ /^.*Deny\s+from\s+(\w+)/)
    {
      $denyValue = $1;
    }
  }

  SecureUtil::DEBUG ("Deny Value = $denyValue");
  if ($denyValue eq $emUploadDeny)
  {
    SecureUtil::USERINFO ("OMS host $vhost already in $lockStatus mode.\n");
    exit 0;
  }

  close(EMCONFH);

  # Get the existing wallet password from httpd_em.conf
  open(EMCONFH, $httpEmConfFile) || die "Could not open $httpEmConfFile";
  my $omsWalletPassword = "";
  while(defined($curLine = <EMCONFH>) && ($omsWalletPassword eq ""))
  {
    chop $curLine;
    if ($curLine =~ /^.*SSLWalletPassword\s+(\w+)/)
    {
        $omsWalletPassword = $1;
    }
  }
  close(EMCONFH);

  SecureUtil::DEBUG ("Wallet Password = $omsWalletPassword");

  # stop httpd if needed
   if( $ohsStatus eq "Up" )
   {
      $rc = stopOHS ($securelog);
      if ($rc eq 0)
      {
        $httpdStatus = "true";
      }
      else
      {
        exit -4;
      }
   }

  # update the httpd conf to restrict http upload
  SecureUtil::USERINFO ("Updating HTTPS Virtual Host for Enterprise Manager OMS...");

  $rc = SecureOMSCmds::configureOHS($securelog, $emUploadHTTPSPort, $emUploadHTTPPort, 
                                $thisDNSHost, $omsWalletPassword, $emUploadDeny, $httpServerTimeout);
  if ($rc eq 0)
  {
    SecureUtil::USERINFO ("   Done.\n");
    # start httpd if needed
    if ($httpdStatus eq "true")
    {
      $rc = startOHS($securelog);
    }
  }
  else
  {
    SecureUtil::USERINFO ("   Failed rc = $rc.\n");
    return $rc;
  }

  if  ("$lockStatus" eq "lock")
  {
    SecureUtil::USERINFO ("OMS Locked. Agents must be Secure and upload over HTTPS Port $statusOut.\n");
  }
  else
  {
    SecureUtil::USERINFO ("OMS Unlocked. Non Secure Agents may upload using HTTP.\n");
  }

  return $rc;
}

sub statusOHS()
{
  my (@args) = @_;
  my $count = scalar(@args);
  my @comp;

  my $i=0;
  while( $i < $count)
  {
     @comp = split /\s+/, $args[$i];
     if(($comp[1] =~ /HTTP/) || ($comp[2] =~ /HTTP/))
     {
        return $comp[3];
     }
     $i = $i + 1;
  }
}

sub startOHS
{
  my $secureLog = $_[0];
  SecureUtil::USERINFO ("Starting the HTTP Server...");
  my $execStr = "$ORACLE_HOME/opmn/bin/opmnctl startproc type=ohs >> $opmnRedirectLog";  
  my $rc = 0xffff & system ($execStr);
  $rc >>= 8;
  if ($rc != 0)
  {
    SecureUtil::USERINFO ("   Failed.\n");
  }
  else
  {
    SecureUtil::USERINFO ("   Done.\n");
  }
  return $rc;
}

sub stopOHS
{
  my $secureLog = $_[0];
  SecureUtil::USERINFO ("Stopping the HTTP Server...");
  my $execStr = "$ORACLE_HOME/opmn/bin/opmnctl stopproc type=ohs >> $opmnRedirectLog";
  my $rc = 0xffff & system($execStr);
  $rc >>= 8;
  if ($rc != 0)
  {
     SecureUtil::USERINFO ("  Failed\n");
     exit $rc;
  }
  else
  {
    SecureUtil::USERINFO ("  Done.\n");
  }
  return $rc;
}


# [] ----------------------------------------------------------------- []

sub genRootKey
{
  my $securelog       = $_[0];
  my $emConsoleMode   = $_[1];
  my $thisDNSHost     = $_[2];
  my $emWalletsDir    = $_[3];

  my $caDir   = "$emWalletsDir/ca.$thisDNSHost";
  SecureUtil::RMRF ($caDir);
  SecureUtil::MKDIRP ($caDir);

  my $dc      = "com";
  my $country = "US";
  my $state   = "CA";
  my $loc     = "EnterpriseManager on $thisDNSHost";
  my $org     = "EnterpriseManager on $thisDNSHost";
  my $unit    = "EnterpriseManager on $thisDNSHost";
  my $email   = "Enterprise.Manager\@$thisDNSHost";


  if ($_[4] ne "") {
    $dc      = $_[4];
    chomp ($dc);
    if(length ($dc) gt 3)
    {
      $dc = substr($dc, 0, 2);
    }
    $dc =~ tr/A-Z/a-z/;
  }
  if ($_[5] ne "") {
    $country = $_[5];
    chomp ($country);
    if(length ($country) gt 2)
    {
      $country = substr($country, 0, 1);
    }
    $country =~ tr/a-z/A-Z/;
  }
  if ($_[6] ne "") {
    $state   = $_[6];
    chomp ($state);
    if(length ($state) gt 2)
    {
      $state = substr($state, 0, 1);
    }
    $state =~ tr/a-z/A-Z/;
  } 
  if ($_[7] ne "") {
    $loc     = $_[7];
    chomp ($loc);
  }
  if ($_[8] ne "") {
    $org     = $_[8];
    chomp ($org);
  }
  if ($_[9] ne "") {
    $unit    = $_[9];
    chomp ($unit);
  }
  if ($_[10] ne "") {
    $email   = $_[10];
    chomp ($email);
  }

  my $rootKeyPassword = $_[11];
  my $resetKey        = $_[12];

  my $javaStr   = "";
  my $classPath = &SecureUtil::getConsoleClassPath($emConsoleMode);
  my $emHome    = &SecureUtil::getEMHome($emConsoleMode);
  my $rc;

  #
  # Call GenRootCert to mke the CA. This class accepts 1 or 2 args depending
  # on whether there already exists an override value for rootKeyPassword. If
  # there is not then GenRootCert will make a random password for the CA.
  #
  # Use Phaos to Generate a Root Key and Certificate in the given location.
  #

  $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DemConsoleMode=$emConsoleMode ".
             "-DrepositoryPropertiesFile=$emHome/sysman/config/emoms.properties ".
             "-Desm.HOSTNAME=\"$thisDNSHost\" ".
             "-Desm.DC=\"$dc\" ".
             "-Desm.COUNTRY=\"$country\" ".
             "-Desm.STATE=\"$state\" ".
             "-Desm.LOC=\"$loc\" ".
             "-Desm.ORG=\"$org \" ".
             "-Desm.ORGUNIT=\"$unit\" ".
             "-Desm.EMAIL=\"$email\" ".
             "-DORACLE_HOME=$ORACLE_HOME ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.RepRootCert -generateCert ".
             ">> $securelog $redirectStderr";

  SecureUtil::DEBUG ("Executing .... $javaStr");

  open(SETPWD, "|$javaStr");
  print SETPWD "$caDir\n";
  print SETPWD "$resetKey\n";
  print SETPWD "$rootKeyPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;

  #
  # Copy the standard trust points to the CA directory for easy inclusion
  # into new wallets
  SecureUtil::CP( "$ORACLE_HOME/sysman/config/b64InternetCertificate.txt", $caDir ); 
  return $rc;
}


sub secureMakeServerWlt
{
  my $oracleHome           = $_[0];
  my $javaHome             = $_[1];
  my $securelog            = $_[2];
  my $emConsoleMode        = $_[3];
  my $walletType           = $_[4];
  my $rootKeyDir           = $_[5];
  my $emWalletsDir         = $_[6];
  my $thisDNSHost          = $_[7];
  my $obfOMSWalletPassword = $_[8];
  my $certName             = $_[9];
  my $rootKeyPassword      = $_[10];
  my $obfEMRootPassword    = $_[11];

  my $serverDN = "";
  my $serverCertDir = "";
  my $javaStr = "";
  my $rc;

  my $classPath = &SecureUtil::getConsoleClassPath($emConsoleMode);

  if ($certName eq "")
  {
    $certName = $thisDNSHost;
  }
  $serverDN      = "cn=$certName";
  $serverCertDir = "$emWalletsDir/$walletType.$thisDNSHost";
  SecureUtil::MKDIRP ($serverCertDir);

  SecureUtil::DEBUG ("Making server wallet for DN = $serverDN");

  $javaStr  = "$javaHome/bin/java ".
              "-cp $classPath ".
              "-DemConsoleMode=$emConsoleMode ".
              " -Ddebug=$debug ".
              "-DORACLE_HOME=$oracleHome ".
              "-DrepositoryPropertiesFile=$oracleHome/sysman/config/emoms.properties ".
              "-Ddebug=$debug ".
              "oracle.sysman.eml.sec.rep.RepWalletUtil -generateWallet ".
              ">> $securelog $redirectStderr";

  SecureUtil::DEBUG ("Executing ... $javaStr");
  
  open(SETPWD, "|$javaStr");
  print SETPWD "$serverDN\n";
  print SETPWD "$serverCertDir\n";
  print SETPWD "$rootKeyDir\n";
  print SETPWD "$obfOMSWalletPassword\n";
  print SETPWD "$obfEMRootPassword\n";
  print SETPWD "$rootKeyPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;
  return $rc;
}


# [] ----------------------------------------------------------------- []

sub genWallet
{
  my $securelog            = $_[0];
  my $emConsoleMode        = $_[1];
  my $thisDNSHost          = $_[2];
  my $obfOMSWalletPassword = $_[3];
  my $rootKeyDir           = $_[4];
  my $certName             = $_[5];
  my $walletType           = $_[6];
  my $obfEMRootPassword    = $_[7];

  my $rootKeyPassword      = "";

  my $emConfigDir          = "$ORACLE_HOME/sysman/config";

  my $emWalletsDir         = "$ORACLE_HOME/sysman/wallets";
  my $agentDownloadDir     = "";
  my $emdIntTrustCertFile  = "";
  my $emdLocalTrustCertFile = "";
  my $emHome               = "";
  my $emWalletFile         = "";
  my $rc;

  if ($emConsoleMode eq "DBCONSOLE")
  {
    $emHome = &SecureUtil::getEMHome($emConsoleMode);
    $emWalletsDir = "$emHome/sysman/wallets";

    $emConfigDir = "$emHome/sysman/config";
  }
  else
  {
    $emHome = $ORACLE_HOME;
  }

  SecureUtil::INFO ("SecureOMSCmds : genWallet : ConsoleMode = $emConsoleMode");
  SecureUtil::INFO ("SecureOMSCmds : genWallet : walletType = $walletType");
  SecureUtil::INFO ("SecureOMSCmds : genWallet : DNSHost = $thisDNSHost");

  #
  # make a new wallet for $thisDNSHost. 
  #
  $rc =  secureMakeServerWlt($emHome, $JAVA_HOME, $securelog, 
                             $emConsoleMode, $walletType, $rootKeyDir, $emWalletsDir, 
                             $thisDNSHost, $obfOMSWalletPassword, $certName, 
                             $rootKeyPassword, $obfEMRootPassword);
  if ($rc ne 0)
  {
    SecureUtil::INFO ("SecureOMSCmds : genWallet : ret code $rc");
    return $rc;
  }

  #
  # stage the new wallet and the trust points to be accessible over
  # the ~/wallets/emd console URL in iAS
  #
  if ($emConsoleMode eq "CENTRAL")
  {
    $agentDownloadDir="$ORACLE_HOME/j2ee/OC4J_EM/applications/em/em/wallets/$walletType.$thisDNSHost";
  }
  elsif ($emConsoleMode eq "DBCONSOLE")
  {
    $agentDownloadDir="$ORACLE_HOME/oc4j/j2ee/oc4j_applications/applications/em/em/wallets/$walletType.$thisDNSHost";
  }
  else
  {
    $agentDownloadDir="$ORACLE_HOME/sysman/webapps/em/wallets/$walletType.$thisDNSHost";
  }
  SecureUtil::INFO ("Agent Download dir = " .$agentDownloadDir);

  if (not (-e $agentDownloadDir))
  {
    SecureUtil::MKDIRP ($agentDownloadDir);
  }

  $emWalletFile="$emWalletsDir/$walletType.$thisDNSHost/ewallet.p12";
  if (not (-e $emWalletFile))
  {
    die "Missing $emWalletFile\n";
  }
  else
  {
    SecureUtil::CP ($emWalletFile, $agentDownloadDir);
  }

  #
  # Pick up the OMS Root CA Certificate from the Oracle Home as this will
  # have been placed here during emctl secure oms ..
  #
  $emdLocalTrustCertFile="$emConfigDir/b64LocalCertificate.txt";
  if (not (-e $emdLocalTrustCertFile))
  {
    die "The EMD local trust cert was not created in $emdLocalTrustCertFile";
  }
  else
  {
    #
    # set up both the b64Local and b64Internet to have the trust point of the
    # console cert signing authority. The console may need to be monitored just
    # like a remote https site on the internet
    #
    SecureUtil::CP ($emdLocalTrustCertFile, "$agentDownloadDir/b64LocalCertificate.txt");
    SecureUtil::CP ($emdLocalTrustCertFile, "$agentDownloadDir/b64InternetCertificate.txt");
  }

  $emdIntTrustCertFile="$emConfigDir/b64InternetCertificate.txt";
  if (not (-e $emdIntTrustCertFile))
  {
    die "The EMD local trust cert was not created in $emdIntTrustCertFile";
  }
  else
  {
    SecureUtil::APPEND ($emdIntTrustCertFile, "$agentDownloadDir/b64InternetCertificate.txt");
  }

  SecureUtil::DEBUG ("Setting B64 Local, Internet CA in Repository...");
  my $classPath = &SecureUtil::getConsoleClassPath($emConsoleMode);
  my $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DrootKeyDir=$rootKeyDir ".
             "-DemConsoleMode=$emConsoleMode ".
             "-DrepositoryPropertiesFile=$emHome/sysman/config/emoms.properties ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.RepRootCert -saveB64Cert ".
             ">> $securelog $redirectStderr";
  
  SecureUtil::DEBUG ("Executing cmd .. $javaStr");
  SecureUtil::DEBUG ("$agentDownloadDir/b64LocalCertificate.txt\n");
  SecureUtil::DEBUG ("$agentDownloadDir/b64InternetCertificate.txt\n");

  open(SETPWD, "|$javaStr");
  print SETPWD "$agentDownloadDir/b64LocalCertificate.txt\n";
  print SETPWD "$agentDownloadDir/b64InternetCertificate.txt\n";
  print SETPWD "$obfEMRootPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;  
  $rc >>= 8;
  if ( $rc eq 0 )     
  {
    SecureUtil::DEBUG ("   Done.");
  }
  else
  {
    SecureUtil::DEBUG ("   Failed.");
  }

  return $rc;
}

# [] ----------------------------------------------------------------- []

sub genKeyStore {
  my $securelog       = $_[0];
  my $emConsoleMode   = $_[1];
  my $thisDNSHost     = $_[2];
  my $rc = SecureUtil::secureGenKeystore ($securelog, $emConsoleMode,
                                          $thisDNSHost, "", "true");
  return $rc;
}

# [] ----------------------------------------------------------------- []

sub secureCentralOMS
{
  my (@args)            = @_;
  my $securelog         = "";
  my $emConsoleMode     = "";
  my $emUploadHTTPPort  = "";
  my $emUploadHTTPSPort = "";
  my $rootPassword      = "";
  my $regPassword       = "";
  my $slbHost           = "";
  my $omsReset          = "";

  my $rc;
  my $stopStatus;

  if (defined($args[0])) {
    $securelog         = $args[0];
  }
  if (defined($args[1])) {
    $emConsoleMode     = $args[1];
  }
  if (defined($args[2])) {
    $emUploadHTTPPort  = $args[2];
  }
  if (defined($args[3])) {
    $emUploadHTTPSPort = $args[3];
  }
  if (defined($args[4])) {
    $rootPassword      = $args[4];
  }
  if (defined($args[5])) {
    $regPassword       = $args[5];
  }
  if (defined($args[6])) {
    $slbHost           = $args[6];
  }
  if (defined($args[7])) {
    $omsReset          = $args[7];
  }

  my $root_dc      = "";
  my $root_country = "";
  my $root_state   = "";
  my $root_loc     = "";
  my $root_org     = "";
  my $root_unit    = "";
  my $root_email   = "";
  my $slbSecUploadPort   = "";

  if (defined($args[8])) {
    $root_dc          = $args[8];
  }
  if (defined($args[9])) {
    $root_country     = $args[9];
  }
  if (defined($args[10])) {
    $root_state       = $args[10];
  }
  if (defined($args[11])) {
    $root_loc         = $args[11];
  }
  if (defined($args[12])) {
    $root_org         = $args[12];
  }
  if (defined($args[13])) {
    $root_unit        = $args[13];
  }
  if (defined($args[14])) {
    $root_email       = $args[14];
  }
  if (defined($args[15])) {
    $slbSecUploadPort = $args[15];
  }

  my $dnsHostName = &EmctlCommon::getLocalHostName();

  if ($emConsoleMode eq "CENTRAL")
  {
    #SecureUtil::USERINFO ("Stopping opmn processes...\n");
    $stopStatus = stopOMS($securelog);
    
    SecureUtil::USERINFO ("Securing central oms...   Started.\n");
    if ($stopStatus eq 0 or $stopStatus eq 1)
    {
      $rc = secureOMS($securelog, $emConsoleMode, $emUploadHTTPPort,
                      $emUploadHTTPSPort, $rootPassword, $regPassword,
                      $slbHost, $omsReset,
                     
                      $root_dc, $root_country, $root_state, $root_loc, $root_org, $root_unit, $root_email,
                      $dnsHostName, $slbSecUploadPort);
      SecureUtil::USERINFO ("Securing central oms...   Ended.\n");
      if ($stopStatus eq 0)
      {
        #SecureUtil::USERINFO ("Restarting opmn processes...\n");
        restartOMS($securelog);
      }
      return $rc;
    }
  }
  else
  {
    SecureUtil::USERINFO ("Securing central oms...   Aborted.\n");
    exit 2;
  }
}

# [] ----------------------------------------------------------------- []

sub secureOMS
{
  my (@args)         = @_;

  my $securelog         = "";
  my $emConsoleMode     = "";
  my $emUploadHTTPPort  = "";
  my $emUploadHTTPSPort = "";
  my $rootPassword      = "";
  my $regPassword       = "";
  my $omsCertName       = "";
  my $resetKey          = "";


  my $obfRootPassword   = "";
  my $omsWalletPwdCmd   = "";
  my $omsWalletPassword = "";
  my $storeRootKey      = "";
  my $rootKeyDir        = "";
  my $javaStr           = "";
  my $execStr           = "";
  my $resetVerify       = "";
  my $rc;
  my @linesRead;
  my $no_changes = 0;
  my $walletOk;
  my @iasobfResultWords;
  my $iasobfResultLen;
  my $iasobfOMSWalletPassword;
  my $printDebugMsg;

  if (defined($args[0])) {
    $securelog         = $args[0];
  }
  if (defined($args[1])) {
    $emConsoleMode     = $args[1];
  }
  if (defined($args[2])) {
    $emUploadHTTPPort  = $args[2];
  }
  if (defined($args[3])) {
    $emUploadHTTPSPort = $args[3];
  }
  if (defined($args[4])) {
    $rootPassword      = $args[4];
  }
  if (defined($args[5])) {
    $regPassword       = $args[5];
  }
  if (defined($args[6])) {
    $omsCertName       = $args[6];
  }
  if (defined($args[7])) {
    $resetKey          = $args[7];
  }

  my $root_dc      = "";
  my $root_country = "";
  my $root_state   = "";
  my $root_loc     = "";
  my $root_org     = "";
  my $root_unit    = "";
  my $root_email   = "";
 
  my $dnsHostName  = ""; #added to get the qualified name of server bug 4294700
  my $thisDNSHost  = "";
  my $slbSecUploadPort = "";

  if (defined($args[8])) {
    $root_dc          = $args[8];
  }
  if (defined($args[9])) {
    $root_country     = $args[9];
  }
  if (defined($args[10])) {
    $root_state       = $args[10];
  }
  if (defined($args[11])) {
    $root_loc         = $args[11];
  }
  if (defined($args[12])) {
    $root_org         = $args[12];
  }
  if (defined($args[13])) {
    $root_unit        = $args[13];
  }
  if (defined($args[14])) {
    $root_email       = $args[14];
  }
  if (defined($args[15])) {
    $dnsHostName      = $args[15];
  }
  if (defined($args[16])) {
    $slbSecUploadPort = $args[16];
  }

  my $emHome            = &SecureUtil::getEMHome($emConsoleMode);

  my $emLibDir          = "$ORACLE_HOME/j2ee/OC4J_EM/applications/em/em/WEB-INF/lib";
  my $emWalletsDir      = "$ORACLE_HOME/sysman/wallets";
  my $classPath         = &SecureUtil::getConsoleClassPath($emConsoleMode);

  if ($dnsHostName ne "")
  {
    $thisDNSHost = $dnsHostName;
  }
  else
  {
    $thisDNSHost       = &EmctlCommon::getLocalHostName();
    $thisDNSHost       =~ s/^\s+|\s+$//;
  }

  # If not certificate name is passed, default to  'hostname'
  if ($omsCertName eq "")
  {
    $omsCertName=$thisDNSHost;
  }

  if ($emConsoleMode eq "CENTRAL")
  {
    $emLibDir  = "$ORACLE_HOME/j2ee/OC4J_EM/applications/em/em/WEB-INF/lib";
  }
  else
  {
    $emLibDir  = "$ORACLE_HOME/sysman/webapps/emd/WEB-INF/lib";
  }

  $rootKeyDir = "$emWalletsDir/ca.$thisDNSHost";

  $storeRootKey = "true";

  SecureUtil::DEBUG ("Obfuscating rootPassword ...");
  my $obfRootPwdCmd = "$JAVA_HOME/bin/java ".
                      " -cp $classPath ".
                      "-DORACLE_HOME=$ORACLE_HOME ".
                      "-Ddebug=$debug ".
                      "oracle.sysman.eml.sec.util.Obfuscate -cypher ";

  SecureUtil::DEBUG ("Executing cmd .. $obfRootPwdCmd ");

  local (*Reader, *Writer);
  my $pid = open2(\*Reader, \*Writer, "$JAVA_HOME/bin/java", "-cp","$classPath","-DORACLE_HOME=$ORACLE_HOME","-Ddebug=$debug","oracle.sysman.eml.sec.util.Obfuscate","-cypher");
  print Writer "$rootPassword\n";
  close Writer;
  while (<Reader>)
  {
    $obfRootPassword = $_;
  }
  close Reader;
  waitpid($pid, 0);

  $obfRootPassword=~ s/^\s+|\s+$//;

  SecureUtil::USERINFO ("Checking Repository...");
  $javaStr = "$JAVA_HOME/bin/java ".
             " -cp $classPath ".
             "-DrepositoryPropertiesFile=$emHome/sysman/config/emoms.properties ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.InstallPassword -auth ".
             ">> $securelog $redirectStderr";

  SecureUtil::DEBUG ("Executing ... $javaStr");
  
  open(SETPWD, "|$javaStr");
  print SETPWD "$rootPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;
  if ( $rc eq 2 )
  {
    SecureUtil::USERINFO ("ERROR. Unable to contact the OMS Repository.\n");
    exit 2;
  }
  else
  {
    if ( $rc eq 0 )
    {
      SecureUtil::USERINFO ("   Done.\n");
    }
    else
    {
      SecureUtil::USERINFO ("   Invalid Password.\n");
      exit 2;
    }
  }

  #
  # check if the emkey is configured properly in the file system
  #

  SecureUtil::USERINFO ("Checking Em Key...   ");
  my $emKeyStatus = EmKeyCmds::verifyEmKey($rootPassword,"false");
    
  if($emKeyStatus eq 0 or $emKeyStatus eq 1 or $emKeyStatus eq 2)
  {
      SecureUtil::USERINFO ("Done.\n");
  }
  else
  {
      SecureUtil::USERINFO ("Failed.\n");
      SecureUtil::USERINFO ("The Em Key is not Configured properly.Run \"emctl status emkey\" for details\n");
      exit 2;
  }


  #
  # check the store to see if a Root Key may already exist. This is true if 
  # we are able to find an existing Root Signing Certificate. If so, do not 
  # overwrite it without an explicit -reset.
  #
  SecureUtil::USERINFO ("Checking Repository for an existing Enterprise Manager Root Key...");
  $storeRootKey  = "true";
  $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DrootKeyDir=$rootKeyDir ".
             "-DemConsoleMode=$emConsoleMode ".
             "-DrepositoryPropertiesFile=$emHome/sysman/config/emoms.properties ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.RepRootCert -checkRootKey ".
             ">> $securelog $redirectStderr";
  SecureUtil::DEBUG ("Executing cmd .. $javaStr");
  open(SETPWD, "|$javaStr");
  print SETPWD "$obfRootPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;
  if ( $rc eq 0 )
  {
    $storeRootKey = "false";
    if( $resetKey eq "")
    {
      SecureUtil::USERINFO ("   Done.\n");
      SecureUtil::INFO ("Root Key in Repository will be reused.\n");
    }
    else
    {
      SecureUtil::USERINFO ("\n");
      SecureUtil::USERINFO ("WARNING! An Enterprise Manager Root Key already exists in\n");
      SecureUtil::USERINFO ("the Repository. This operation will replace your Enterprise\n");
      SecureUtil::USERINFO ("Manager Root Key.\n");
      SecureUtil::USERINFO ("");
      SecureUtil::USERINFO ("All existing Agents that use HTTPS will need to be\n");
      SecureUtil::USERINFO ("reconfigured if you proceed. Do you wish to continue and\n");
      SecureUtil::USERINFO ("overwrite your Root Key\n");
      SecureUtil::USERINFO ("(Y/N) ?\n");
      $resetVerify=<STDIN>;
      chomp ($resetVerify);
      if ($resetVerify eq "Y")
      { 
        SecureUtil::USERINFO ("");
        SecureUtil::USERINFO ("Are you sure ? Reset of the Enterprise Manager Root Key\n");
        SecureUtil::USERINFO ("will mean that you will need to reconfigure each Agent\n");
        SecureUtil::USERINFO ("that is associated with this OMS before they will be\n");
        SecureUtil::USERINFO ("able to upload any data to it. Monitoring of Targets\n");
        SecureUtil::USERINFO ("associated with these Agents will be unavailable until\n");
        SecureUtil::USERINFO ("after they are reconfigured.\n");
        SecureUtil::USERINFO ("(Y/N) ?\n");
        $resetVerify=<STDIN>;
        chomp ($resetVerify);
        if ($resetVerify eq "Y")
        {
          $storeRootKey = "true";
        }
        else
        {
          exit 0;
        }
      }
      else
      {
        exit 0;
      }
    }
  }
  else
  {
    SecureUtil::USERINFO ("   Done.\n");
  }
  if ($storeRootKey eq "true")
  {
    SecureUtil::USERINFO ("Generating Enterprise Manager Root Key (this takes a minute)...");
    if ($resetKey eq "")
    {
        $resetKey = "false";
    }
    else
    {
        $resetKey = "true";
    }
    my $rootKeyOk = genRootKey($securelog, $emConsoleMode, $thisDNSHost, $emWalletsDir,
                               $root_dc, $root_country, $root_state, $root_loc, $root_org, $root_unit, $root_email,
                               $obfRootPassword, $resetKey);
    if ($rootKeyOk eq 0)
    {
      SecureUtil::USERINFO ("   Done.\n");
    }
    else
    {
      SecureUtil::USERINFO ("Failed to create Enterprise Manager Root Key.\n");
      exit 2;
    }
  }

  #
  # save the CA Certificate in the location used by the Console for its
  # trustpoint during outbound java ssl connections
  #
  SecureUtil::USERINFO ("Fetching Root Certificate from the Repository...");
  my $b64TextFile = "$emHome/sysman/config/b64LocalCertificate.txt";
  $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DemConsoleMode=$emConsoleMode ".
             "-DrepositoryPropertiesFile=$emHome/sysman/config/emoms.properties ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.RepRootCert -saveCert ".
             ">> $securelog $redirectStderr";
  SecureUtil::DEBUG ("Executing cmd .. $javaStr");

  open(SETPWD, "|$javaStr");
  print SETPWD "$b64TextFile\n";
  print SETPWD "$obfRootPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;
  if ( $rc eq 0 )
  {
    SecureUtil::USERINFO ("   Done.\n");
  }
  else
  {
    SecureUtil::USERINFO ("   Failed. rc = $rc\n");
    exit $rc;
  }

  SecureUtil::USERINFO ("Generating Registration Password Verifier in the Repository...");
  $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DemConsoleMode=$emConsoleMode ".
             "-DrepositoryPropertiesFile=$emHome/sysman/config/emoms.properties ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.InstallPassword -noauth ".
             ">> $securelog $redirectStderr";

  SecureUtil::DEBUG ("Executing ... $javaStr");
  
  open(SETPWD, "|$javaStr");
  print SETPWD "$regPassword\n";
  print SETPWD "$obfRootPassword\n";
  close(SETPWD);

  $rc = 0xffff & $?;
  $rc >>= 8;
  if ( $rc eq 0 )
  {
    SecureUtil::USERINFO ("   Done.\n");
  }
  else
  {
    SecureUtil::USERINFO ("   Failed.\n");
    if ( $rc eq 2 )
    {
      SecureUtil::USERINFO ("The Agent Registration Password you supplied does not match the Verifier set in this Repository.\n");
    }
    exit $rc;
  }

  if ($emConsoleMode eq "CENTRAL")
  {
    #
    # Generate a random password to be used for the OMS Oracle Wallet
    #
    SecureUtil::USERINFO ("Generating Oracle Wallet Password for Enterprise Manager OMS...");
    $omsWalletPwdCmd = "$JAVA_HOME/bin/java ".
                       "-cp $classPath ".
                       "oracle.sysman.util.crypt.Verifier -genPassword";

    SecureUtil::DEBUG ("Executing cmd ... $omsWalletPwdCmd");
    $omsWalletPassword = `$omsWalletPwdCmd`;
    $omsWalletPassword=~ s/^\s+|\s+$//;
    SecureUtil::USERINFO ("   Done.\n");

    #
    # Obtain obfuscated values for the input passwords
    #
    SecureUtil::USERINFO ("Generating Oracle Wallet for Enterprise Manager OMS...");
    SecureUtil::DEBUG ("Obfuscating OMS wallet password...");
    my $obfOMSWalletPwdCmd = "$JAVA_HOME/bin/java ".
                             " -cp $classPath ".
                             "-DORACLE_HOME=$ORACLE_HOME ".
                             "-Ddebug=$debug ".
                             "oracle.sysman.eml.sec.util.Obfuscate -cypher ";

    SecureUtil::DEBUG ("Executing cmd .. $obfOMSWalletPwdCmd ");

    my $obfOMSWalletPassword;
    local (*Reader, *Writer);
    my $pid = open2(\*Reader, \*Writer, "$JAVA_HOME/bin/java", "-cp","$classPath","-DORACLE_HOME=$ORACLE_HOME","-Ddebug=$debug","oracle.sysman.eml.sec.util.Obfuscate","-cypher");
    print Writer "$omsWalletPassword\n";
    close Writer;
    while (<Reader>)
    {
      $obfOMSWalletPassword = $_;
    }
    close Reader;
    waitpid($pid, 0);

    $obfOMSWalletPassword=~ s/^\s+|\s+$//;

    #
    # Use genwallet to make the Oracle Wallet that will be used by the OMS for
    # https upload. Pass in OMS_CERT_NAME to be used if it has a value to
    # override the name goven to the OMS in its certificate
    #
    $walletOk = genWallet ($securelog, $emConsoleMode, $thisDNSHost,
                           $obfOMSWalletPassword, "rep", $omsCertName,
                           "oms", $obfRootPassword);
    if ($walletOk eq 0)
    {
      SecureUtil::USERINFO ("   Done.\n");
    }
    else
    {
      SecureUtil::USERINFO ("   Failed.\n");
      return $walletOk;
    }

    #
    # Use genwallet to make another Oracle Wallet that may be used by iAS
    # for https browser access, just in case one does not exist and the user
    # has no current means to obtain one.
    #
    # Since we are offering a Wallet that may be used by Apache as a courtesy
    # in the event of one not exiting at all then it is ok to seed this wallet
    # with a random iAS HTTP Server Wallet Password. If the user
    # decides to use this Wallet for their iAS Web Server then they should
    # change the password and configure their HTTP Server accordingly.
    #
    SecureUtil::USERINFO ("Generating Oracle Wallet for iAS HTTP Server...");
    my $IASWalletPasswordCmd = "$JAVA_HOME/bin/java ".
                       "-cp $classPath ".
                       "oracle.sysman.util.crypt.Verifier -genPassword";
    my $IASWalletPassword = `$IASWalletPasswordCmd`;
    $IASWalletPassword =~ s/^\s+|\s+$//;

    my $obfIASWalletPwdCmd = "$JAVA_HOME/bin/java ".
                             " -cp $classPath ".
                             "-DORACLE_HOME=$ORACLE_HOME ".
                             "-Ddebug=$debug ".
                             "oracle.sysman.eml.sec.util.Obfuscate -cypher ";

    SecureUtil::DEBUG ("Executing cmd .. $obfOMSWalletPwdCmd ");

    my $obfIASWalletPassword;
    local (*Reader, *Writer);
    my $pid = open2(\*Reader, \*Writer, "$JAVA_HOME/bin/java", "-cp","$classPath","-DORACLE_HOME=$ORACLE_HOME","-Ddebug=$debug","oracle.sysman.eml.sec.util.Obfuscate","-cypher");
    print Writer "$IASWalletPassword\n";
    close Writer;
    while (<Reader>)
    {
      $obfIASWalletPassword = $_;
    }
    close Reader;
    waitpid($pid, 0);

    $obfIASWalletPassword=~ s/^\s+|\s+$//;

    $walletOk = genWallet ($securelog, $emConsoleMode, $thisDNSHost, 
                           $obfIASWalletPassword, "rep", $omsCertName, 
                           "ias", $obfRootPassword);
    if ($walletOk eq 0)
    {
      SecureUtil::USERINFO ("   Done.\n");
    }
    else
    {
      SecureUtil::USERINFO ("   Failed.\n");
      return $walletOk; 
    }
  }

  #
  # save the upload https port number in emoms.properties
  #
  SecureUtil::USERINFO ("Updating HTTPS port in emoms.properties file...");
  $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DemConsoleMode=$emConsoleMode ".
             "-DrepositoryPropertiesFile=$emHome/sysman/config/emoms.properties ".
             "-Ddebug=$debug ".
             "oracle.sysman.eml.sec.rep.SetProperty $emUploadHTTPSPort $slbSecUploadPort ".
             ">> $securelog $redirectStderr";
  SecureUtil::DEBUG ("Executing cmd .. $javaStr");
  $rc = 0xffff & system($javaStr);
  $rc >>= 8;
  if ( $rc eq 0 )
  {
    SecureUtil::USERINFO ("   Done.\n");
  }
  else
  {
    SecureUtil::USERINFO ("   Failed. rc = $rc\n");
    exit $rc;
  }

  if ($emConsoleMode eq "CENTRAL")
  {
    SecureUtil::USERINFO ("Generating HTTPS Virtual Host for Enterprise Manager OMS...");

    my $iasObfCmd = "$ORACLE_HOME/Apache/Apache/bin/iasobf ";

    if ("$IS_WINDOWS" eq "TRUE")
    {
      $iasObfCmd = "$ORACLE_HOME/Apache/Apache/bin/osslpassword.exe ";
    }


    # get ias obfuscated passsword from iasobf utility
    my $iasobfOMSWalletPwdCmd = "$iasObfCmd -p $omsWalletPassword";

    SecureUtil::DEBUG ("Executing cmd .. $iasObfCmd -p ######");
    my $iasobfOMSWalletPwdCmdResult = `$iasobfOMSWalletPwdCmd`;

    # parse results for password (last string in results returned)
    @iasobfResultWords = split (/ /, $iasobfOMSWalletPwdCmdResult);
    $iasobfResultLen = @iasobfResultWords;
    $iasobfOMSWalletPassword = $iasobfResultWords[$iasobfResultLen-1];   
    $iasobfOMSWalletPassword=~ s/^\s+|\s+$//;
    
    SecureUtil::DEBUG ("Obfuscated iasobfOMSWalletPwd = $iasobfOMSWalletPassword ");

    $rc = configureOHS($securelog, $emUploadHTTPSPort, $emUploadHTTPPort,
                       $thisDNSHost, $iasobfOMSWalletPassword, "none", $httpServerTimeout);

    if ($rc eq 0)
    {
      SecureUtil::USERINFO ("   Done.\n");
    }
    else
    {
      SecureUtil::USERINFO ("   Failed rc = $rc.\n");
      return $rc;
    }
  }
  else
  {
    #
    # This "OMS" is really a Standalone OC4J and needs a Keystore
    #
    SecureUtil::USERINFO ("Generating Java Keystore...");
    my $keyStoreOk = genKeyStore ($securelog, $emConsoleMode, $omsCertName);
    if (not $keyStoreOk eq 0)
    {
      SecureUtil::USERINFO ("   Failed.\n");
      exit $rc;
    }
    SecureUtil::USERINFO ("   Done.\n");
  }
  return 0;
}

sub configureOHS
{
  my $securelog         = $_[0];
  my $emUploadHTTPSPort = $_[1];
  my $emUploadHTTPPort  = $_[2];
  my $thisDNSHost       = $_[3];
  my $omsWalletPassword = $_[4];
  my $emUploadDeny      = $_[5];
  my $httpServerTimeout = $_[6];

  my $rc = 0;

  SecureUtil::INFO ("Enabling SSL for Oracle HTTP Server ...");
  # Modify opmn.xml to ensure that OHS is started with ssl-enabled.
  $rc = enableSSLForOHS($securelog);
  if ($rc eq 0)
  {
    SecureUtil::INFO ("   Done.\n");
  }
  else
  {
    SecureUtil::INFO ("   Failed rc = $rc.\n");
    return $rc;
  }


  SecureUtil::INFO ("Generating HTTPS Virtual Host for Enterprise Manager OMS...");
  # Instantiate httpd_em.conf.template
  my $httpEmConfTemplateFile = "$ORACLE_HOME/sysman/config/httpd_em.conf.template";
  my $httpEmConfFile         = "$ORACLE_HOME/sysman/config/httpd_em.conf";

  my @var_names = ("&EM_UPLOAD_HTTPS_PORT&", "&EM_UPLOAD_HTTP_PORT&", "&ORACLE_HOME&",
                   "&THIS_DNS_HOST&", "&OMS_WALLET_PASSWORD&", 
                   "&EM_UPLOAD_DENY&", "&EM_VHOST&", "&TIMEOUT&");

  my @var_values =("$emUploadHTTPSPort",     "$emUploadHTTPPort", "$ORACLE_HOME",
                   "$thisDNSHost", "$omsWalletPassword",
                   "$emUploadDeny", "$thisDNSHost", "$httpServerTimeout");

  $rc = SecureUtil::REPLACE($httpEmConfTemplateFile, $httpEmConfFile, \@var_names, \@var_values);

  if ($rc eq 0)
  {
    SecureUtil::INFO ("   Done.\n");
  }
  else
  {
    SecureUtil::INFO ("   Failed rc = $rc.\n");
    return $rc;
  }

  # Update DCM configuration
  # bug 3048273. inform DCM about config changes
  SecureUtil::DEBUG("Updating DCM config info...");
  my $dcmCmd = "$ORACLE_HOME/dcm/bin/dcmctl updateconfig -ct ohs >> $opmnRedirectLog";
  $rc = 0xffff & system($dcmCmd);
  $rc >>= 8;
  if ($rc eq 0)
  {
    SecureUtil::DEBUG("  Done.\n");
  }
  else
  {
    SecureUtil::DEBUG("  Failed.\n");
    return $rc;
  }

  return $rc;
}

sub enableSSLForOHS
{
  my $securelog       = $_[0];

  my $sslDisabled     = 0;
  my $rc              = 0;

  my $opmnConfigFileOrig = "$ORACLE_HOME/opmn/conf/opmn.xml";
  my $opmnConfigFileNew  = "$ORACLE_HOME/opmn/conf/opmn.xml.$$";

  SecureUtil::INFO ("Enabling SSL for OHS in opmn.xml ...");

  open(FILE, $opmnConfigFileOrig) or die "Can not read targets file($opmnConfigFileOrig)";
  my @linesRead = <FILE>;
  close(FILE);

  ;# Enable only if SSL is disabled.
  foreach $_ (@linesRead) 
  {
    if (/data.*start-mode.*ssl-disabled/) 
    {
       $sslDisabled = 1;
    }
  }

  if ($sslDisabled eq 1)
  {
    ;# Walk the lines, and write to new file
    if ( open(FILE,">" . $opmnConfigFileNew) )  
    {
      foreach $_ (@linesRead) 
      {
        ;# Change ssl-disabled to ssl-enabled
        if (/data.*start-mode.*ssl-disabled/) 
        {
          s/ssl-disabled/ssl-enabled/;
        }
        ;# Print the property line
        print(FILE $_);
      }
      close(FILE);
    } 
    else 
    {
      die "Can not write new OPMN.XML ($opmnConfigFileNew)";
    }

    if (! rename $opmnConfigFileOrig, "$opmnConfigFileOrig.bak.$$") 
    {
      die "Could not rename OPMN config file\n$!\n";
    }
    if (! rename $opmnConfigFileNew, $opmnConfigFileOrig) 
    {
      die "Could not rename new OPMN config file\n$!\n";
    }
  }
     
  SecureUtil::INFO ("   Done.\n");
  return $rc;
}


sub stopOMS()
{
  my $rc;
  my $securelog     = $_[0];
  my $omsStopStr    = "$ORACLE_HOME/opmn/bin/opmnctl stopall >> $opmnRedirectLog";
  my $omsStartStr   = "$ORACLE_HOME/opmn/bin/opmnctl startall >> $opmnRedirectLog";
  my $omsStatusStr  = "$ORACLE_HOME/opmn/bin/opmnctl status >> $opmnRedirectLog";

  $rc = 0xffff & system($omsStatusStr);
  $rc >>= 8;
  if ($rc eq 0)
  {
    system($omsStopStr);
    $rc = 0xffff & system($omsStatusStr);
    $rc >>= 8;
    if ($rc eq 0)
    {
      SecureUtil::USERINFO ("Failed to stop opmn processes...\n");
      exit 2;
    }
    elsif ($rc eq 2)
    {
      SecureUtil::USERINFO ("OPMN processes successfully stopped...   Done.\n");
      return 0;
    }
    else
    {
      my $tries=30;
      while( $tries gt 0 )
      {
        sleep 1;
        $rc = 0xffff & system($omsStatusStr);
        $rc >>= 8;
        if ($rc ne 2)
        {
          last;
        }
        $tries = $tries-1;
        print ".";
      }
      $rc = 0xffff & system($omsStatusStr);
      $rc >>= 8;
      if ($rc eq 2)
      {
        SecureUtil::USERINFO ("OPMN processes successfully stopped...   Done.\n");
        return 0;
      }
      else
      {
        SecureUtil::USERINFO ("Failed to stop opmn processes...\n");
        SecureUtil::DEBUG ("Error: $rc...\n");     
        exit 2;
      }
    }
  }
  elsif ($rc eq 2)
  {
    SecureUtil::USERINFO ("OPMN processes already stopped...   Done.\n");
    return 1;
  }
  else
  {
    my $tries=30;
    while( $tries gt 0 )
    {
      sleep 1;
      $rc = 0xffff & system($omsStatusStr);
      $rc >>= 8;
      if ($rc ne 2)
      {
        last;
      }
      $tries = $tries-1;
      print ".";
    }
    $rc = 0xffff & system($omsStatusStr);
    $rc >>= 8;
    if ($rc eq 2)
    {
      SecureUtil::USERINFO ("OPMN processes successfully stopped...   Done.\n");
      return 0;
    }
    else
    {
      SecureUtil::USERINFO ("Failed to stop opmn processes...\n");
      SecureUtil::DEBUG ("Error: $rc...\n");   
      exit 2;
    }
  }
}

sub restartOMS
{
  my $rc;
  my $securelog     = $_[0];
  my $omsStopStr    = "$ORACLE_HOME/opmn/bin/opmnctl stopall >> $opmnRedirectLog";
  my $omsStartStr   = "$ORACLE_HOME/opmn/bin/opmnctl startall >> $opmnRedirectLog";
  my $omsStatusStr  = "$ORACLE_HOME/opmn/bin/opmnctl status >> $opmnRedirectLog";
  
  system($omsStartStr);
  $rc = 0xffff & system($omsStatusStr);
  $rc >>= 8;
  if ($rc eq 0)
  {
    SecureUtil::USERINFO ("OPMN processes successfully restarted...   Done.\n");
    return 0;
  }
  elsif ($rc eq 2)
  {
    SecureUtil::USERINFO ("Failed to restart opmn processes...\n");
    exit 2;
  }
  else
  {
    my $tries=30;
    while( $tries gt 0 )
    {
      sleep 1;
      $rc = 0xffff & system($omsStatusStr);
      $rc >>= 8;
      if ($rc ne 0)
      {
        last;
      }
      $tries = $tries-1;
      print ".";
    }
    $rc = 0xffff & system($omsStatusStr);
    $rc >>= 8;
    if ($rc eq 0)
    {
      SecureUtil::USERINFO ("OPMN processes successfully restarted...   Done.\n");
      return 0;
    }
    else
    {
      SecureUtil::USERINFO ("Failed to restart opmn processes...\n");
      SecureUtil::USERINFO ("Error: $rc...\n");
      exit 2;
    }
  }
}


#
# get http port for the console from httpd_em.conf file. We are looking for 
# the port for the  <VirtualHost *:port> which is not in <IfDefine SSL>
# </IfDefine> block. Also look for https port
#
sub getOMSPorts {
  my(@args) = @_;
  my $httpEmConfFile         = "$ORACLE_HOME/sysman/config/httpd_em.conf";
  my $sslStart               = "<IfDefine SSL>";
  my $sslStop                = "<\/IfDefine>";
  my $emConsoleHttpPort = "";
  my $emConsoleHttpsPort = "";
  my @returnArray = ();

  open(EMCONFH, $httpEmConfFile) || die "Could not open $httpEmConfFile\n";
  my $curLine;
  my $insideSSL = 0;
  while(defined($curLine = <EMCONFH>))
  {
    chop $curLine;
    if ($curLine =~ /^.*<VirtualHost\s+\*:(\d+)>/)
    {
       if ($insideSSL == 0)
       {
         $emConsoleHttpPort = $1;
       }
       else
       {
         $emConsoleHttpsPort = $1;
       }
    }
    if ($curLine =~ /^$sslStart/) 
    {
      $insideSSL = 1;
    }
    if ($curLine =~ /^$sslStop/)
    {
      $insideSSL = 0;
    }
  }
  close(EMCONFH);

  SecureUtil::DEBUG (
              "Http upload port from httpd_em.conf is $emConsoleHttpPort\n");
  SecureUtil::DEBUG (
              "Https upload port from httpd_em.conf is $emConsoleHttpsPort\n");

  (@returnArray) = ($emConsoleHttpPort, $emConsoleHttpsPort);
  return (\@returnArray);
  
}


sub sso
{
  local (*args) = @_;
  my $retVal    = "";
  parsecommand(@args);
  if ($debugFlag eq "true")
  {
    SecureUtil::setDebug("true");
  }
  verifyparams();
  modifyconfig();
  modifyprop();
  $retVal = registersso();

  # Must exit here as this gets called as a require from emctl.pl
  return $retVal;
}


# get command line options
sub parsecommand()
{
    @args = @_;
    if ($#args < 10)
    {
      print "\nERROR: Not enough arguments\n\n";
      printusage();
      exit;
    }

    while ($#args > 0)
    {
      $_ = shift(@args);
      
      # mendatory arguments
      if (/^-host/)
      {
          $serverhost = shift(@args);
      }
      elsif (/^-port/)
      {
          $serverport = shift(@args);
      }
      elsif (/^-sid/)
      {
          $serversid = shift(@args);
      }
      elsif (/^-pass/)
      {
          $serverpwd = shift(@args);
      }
      elsif (/^-das/)
      {
          $dasurl = shift(@args);
      }
      elsif (/^-u/)
      {
          $user = shift(@args);
      }
      # optional arguments
      elsif (/^-d/)
      {
          $debugFlag = shift(@args);
      }
      else
      {
          print "\nERROR: Unknow argument: $_\n\n";
          printusage();
          exit;
      }
    }
}

sub printusage()
{
    print "Usage:\n";
    print "       emctl config oms sso -host ssoHost -port ssoPort -sid ssoSid -pass ssoPassword -das dasURL -u user\n";
    print "       ssoHost: has to be a fully qualified host name\n";
    print "       dasURL: http://host:port -- host is ssoHost, port is http port\n";
    print "       user: the user that will start the HTTP server.\n";
    print "Example:\n";
    print "       emctl config oms sso -host ssohost.example.com -port 1521 -sid iasdb -pass ### -das http://ssohost.example.com:7777 -u oracle\n";
    print "Options:\n";
    print "       [-d true] -- Turn on debug flag.\n";
}

# read parameters from a file
# - not used
sub readparam()
{
    my ($file) = @_;
    SecureUtil::USERINFO ("Read parameters from $file\n");
    open(PARAMFILE, "<$file") || die "Cannot open $file\n";
    while (<PARAMFILE>)
    {
      /^OracleHome=(.*)/ && ($ohm = $1);
      /^Hostname=(.*)/ && ($hostname = $1);
      /^HostPort=(.*)/ && ($port = $1);
      /^HostDomain=(.*)/ && ($domain = $1);
      /^User=(.*)/ && ($user = $1);
      /^ConfigFile=(.*)/ && ($configfile = $1);
      /^PropertyFile=(.*)/ && ($propfile = $1);
      /^ServerHost=(.*)/ && ($serverhost = $1);
      /^ServerPort=(.*)/ && ($serverport = $1);
      /^ServerSid=(.*)/ && ($serversid = $1);
      /^ServerSchema=(.*)/ && ($serverschema = $1);
      /^ServerPwd=(.*)/ && ($serverpwd = $1);
      /^ServerWebPort=(.*)/ && ($serverwebport = $1);
    }
}

# get params from Apache configuration file
# - not used
sub getParameters()
{
    my $port2 = "";
    SecureUtil::USERINFO ("Get parameters from $configfile\n");
    open(CONFFILE, "<$configfile") || die "Cannot open $configfile\n";

    while (<CONFFILE>) {
        # - get the last line (none ssl)
        if(/^ServerName (.*)/) {
            $hostname = $1;
            print "hostname=$hostname\n";
            $_ = $hostname;
            if($hostname =~ /^[\w_-]+\.(.*)/) { $domain=$1;}
        }
        if($port !~ /\d+/) {
            /^Listen (\d+)/ &&  ($port = $1);
            /^Port (\d+)/ &&    ($port2 = $1);
        }
        if($user !~ /\w/) {
            /^User (.*)/ && ($user = $1);
        }
    }
    close(CONFFILE);

    if ($port !~ /\d+/) {
        $port = $port2;
    }
}

# get the values if not set in parameter files
sub verifyparams()
{
    SecureUtil::DEBUG ("Verifing parameters...");

    die "No hostname specified" unless $hostname;
    die "No port specified" unless $port;
    die "No user specified" unless $user;

    # check instantiation
    die "ORACLE_HOME not instantiated" unless ($ohm !~ /\%/); 
    die "SITE_HOST not instantiated" unless ($hostname !~ /\%/); 
    die "SITE_PORT not instantiated" unless ($port !~ /\%/); 
    die "USER not instantiated" unless ($user !~ /\%/); 
    die "CONSOLE_PROPERTIES not instantiated" unless ($propfile !~ /\%/); 

    if($hostname =~ /^[\w_-]+\.(.*)/)
    {
      $domain=$1;
    }

    die "domain name empty - $hostname must be a fully qualified host name" unless $domain;

    SecureUtil::DEBUG ("SSO server: ssoHost=$serverhost");
    SecureUtil::DEBUG ("            ssoPort=$serverport");
    SecureUtil::DEBUG ("            ssoSid=$serversid");
    SecureUtil::DEBUG ("            ssoSchema=$serverschema");
    SecureUtil::DEBUG ("            ssoPassword=$serverpwd");
    SecureUtil::DEBUG ("            dasurl=$dasurl");
    SecureUtil::DEBUG ("LocalHost: hostname=$hostname");
    SecureUtil::DEBUG ("           port=$port");
    SecureUtil::DEBUG ("           oraclehome=$ohm");
    SecureUtil::DEBUG ("           domain=$domain");
    SecureUtil::DEBUG ("           user=$user");
    SecureUtil::DEBUG ("           configfile=$configfile");
    SecureUtil::DEBUG ("           propfile=$propfile");

}

# Modify Apache configuration file
sub modifyconfig()
{
    SecureUtil::USERINFO ("Modifying HTTP configuration file...");
    open(CONFFILE, "<$configfile") || die "Cannot open $configfile\n";
    open(TEMPFILE, ">$tempfile") || die "Cannot open $tempfile\n";

    my $change = 0;
    while (<CONFFILE>)
    {
      if (/^\#include\s\S+mod_osso\.conf/)
      {
          s/\#//; 
          $change=1;
      }
      print TEMPFILE;
    }
    close(CONFFILE);
    close(TEMPFILE);

    if ($change == 1)
    {
      rename($configfile, "$configfile-emsso.bak");
      rename($tempfile, $configfile);
      SecureUtil::DEBUG ("$configfile has been modified.\n");
      SecureUtil::USERINFO ("   Done.\n");
    }
    else
    {
      SecureUtil::DEBUG ("$configfile has already been set to enable SSO.\n");
      SecureUtil::USERINFO ("   Done.\n");
    }
}

#
# Modify EM Console configuration file
#
sub modifyprop()
{
    SecureUtil::USERINFO ("Modifying console configuration file...");
    open(PROPFILE, "<$propfile") || die "Cannot open $propfile\n";
    open(TEMPFILE, ">$tempfile") || die "Cannot open $tempfile\n";

    die "No Domain value is defined" unless $domain;

    my $auth = 0;
    my $das = 0;
    my $dom = 0;
    while (<PROPFILE>)
    {
      if (/oracle.sysman.emSDK.sec.DirectoryAuthenticationType=(.*)/)
      {
          s/^\S+$1/oracle.sysman.emSDK.sec.DirectoryAuthenticationType=SSO/;
          $auth = 1;
          SecureUtil::DEBUG ("Set DirectoryAuthenticationType=SSO");
      }
      elsif (/oracle.sysman.emSDK.sec.sso.DASHostUrl=(.*)/)
      {
          s/^\S+$1/oracle.sysman.emSDK.sec.sso.DASHostUrl=$dasurl/;
          $das = 1;
          SecureUtil::DEBUG ("Set DASHostUrl to $dasurl");
      }
      elsif (/oracle.sysman.emSDK.sec.sso.Domain=(.*)/)
      {
          s/^\S+$1/oracle.sysman.emSDK.sec.sso.Domain=$domain/;
          $dom = 1;
          SecureUtil::DEBUG ("Set Domain to $domain");
      }
      print TEMPFILE;
    }

    # if didn't find the line, add one
    if ($auth == 0)
    {
      print TEMPFILE "\noracle.sysman.emSDK.sec.DirectoryAuthenticationType=SSO";
      SecureUtil::DEBUG ("Add oracle.sysman.emSDK.sec.DirectoryAuthenticationType=SSO");
    }
    if ($das == 0)
    {
      print TEMPFILE "\noracle.sysman.emSDK.sec.sso.DASHostUrl=$dasurl";
      SecureUtil::DEBUG ("Add oracle.sysman.emSDK.sec.sso.DASHostUrl=$dasurl");
    }
    if ($dom == 0)
    {
      print TEMPFILE "\noracle.sysman.emSDK.sec.sso.Domain=$domain";
      SecureUtil::DEBUG ("Add oracle.sysman.emSDK.sec.sso.Domain=$domain");
    }

    close(PROPFILE);
    close(TEMPFILE);

    rename($propfile, "$propfile-sso.bak");
    rename($tempfile, $propfile);
    SecureUtil::DEBUG ("$propfile has been modified.\n");
    SecureUtil::USERINFO ("   Done.\n");
}

sub registersso()
{
    my $cmd  = "$ohm/jdk/bin/java -jar $ohm/sso/lib/ossoreg.jar -oracle_home_path $ohm";
    my $arg1 = "-host $serverhost -port $serverport -sid $serversid -schema $serverschema -pass $serverpwd";
    my $arg2 = "-site_name $hostname:$port -success_url http://$hostname:$port/osso_login_success"; 
    my $arg3 = "-logout_url  http://$hostname:$port/osso_logout_success";
    my $arg4 = "-cancel_url http://$hostname:$port/ -home_url http://$hostname:$port/";
    my $arg5 = "-config_mod_osso TRUE -u $user -sso_server_version v1.2";
    
    $cmd = "$cmd $arg1 $arg2 $arg3 $arg4 $arg5";
    SecureUtil::USERINFO ("Registering to SSO server, please wait...\n");
    SecureUtil::DEBUG ($cmd);
    my $rc = 0xffff & system($cmd);
    my $exitVal = $rc >> 8;
    if($exitVal)
    {
      SecureUtil::USERINFO ("Failed. Error:$exitVal\n");
      SecureUtil::DEBUG ("Failed executing $cmd.\n[$?;$exitVal;$!]\n");
    }
    else
    {
      SecureUtil::USERINFO ("   Done.\n");
    }
    return $exitVal;
}

sub debug()
{
    my($msg) = @_;
    print "DEBUG: $msg\n" unless !$debugFlag;
}


sub displaySecureOMSCmdsHelp
{
  print "Help!\n";
}

1;


