# 
# $Header: emdb/scripts/unix/SecureDBConsoleCmds.pm /st_emdbsa_11.2.0.4.0dbpsu-spu/1 2015/01/27 09:42:44 mkiran Exp $
#
# NAME : setup_env.pl
#
# PURPOSE : secure commands impl for emctl secure.
#
#    MODIFIED   (MM/DD/YY)
#    mkiran      01/27/15 - 19788842: Change $EM_SOL_JAVA to $EmctlCommon::EM_SOL_JAVA
#                           (Backport fix 19788842 to st_emdbsa_11.2.0.4.0dbpsu-spu)
#    dchakumk    08/08/13 - bug 17246576
#    pratejai    09/03/12 - Fix for bug 14503114.
#    pchebrol    07/08/11 - RFI 12337159 - strong sign algo
#    pchebrol    03/24/10 - Bug 9076753 - set cipher suites
#    pchebrol    07/15/09 - Bug 8656846 - dont redirect
#    pchebrol    06/11/09 - LRG 3928827 - remove hard-coded pwd
#    pchebrol    09/25/08 - Bug 7225691 - support third party certs
#    pchebrol    09/07/08 - Bug 7270949
#    pchebrol    08/06/08 - bug 6345466 - pass jit option as a workaround
#    pchebrol    06/18/08 - osdt_cert3 & osdt_core3 deprecated
#    sresrini    12/04/07 - upgrade to oc4j10.1.3.3 11gjdbc stack
#    misun       06/27/07 - fix the bug 6157677: remove the "unsecure" keyword
#                           when the user runs "emctl -help"
#    rpinnama    06/07/07 - Fix 6119351 : Support securing RAC nodes
#    rpinnama    05/01/07 - Cutover to single java invocation
#    shianand    09/29/06 - fix bug 5520464
#    shianand    09/25/06 - fix bug 5556081
#    shianand    09/04/06 - fix bug 4766676
#    shianand    07/24/06 - fix bug 4571079 (remove mkwallet implmentation) 
#    shianand    07/24/06 - fix bug 5501915 
#    vivsharm    05/10/06 - 
#    anosriva    05/10/06 - 
#    vivsharm    05/09/06 - move over dbconsole to emdb
#

package SecureDBConsoleCmds;

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

use Getopt::Long;


use EmctlCommon;

use SecureUtil;
use DBConsole;

my $ORACLE_HOME       = $ENV{ORACLE_HOME};
my $ORACLE_SID        = $ENV{ORACLE_SID};
my $JAVA_HOME         = $ENV{JAVA_HOME};
my $emUploadHTTPPort  = $ENV{EM_UPLOAD_PORT};
my $emUploadHTTPSPort = $ENV{EM_UPLOAD_HTTPS_PORT};
my $IS_WINDOWS        = "";
my $redirectStderr    = "2>&1";
my $isSecRemoteNode   = "false";
my $remoteStateDir    = "";
my $remoteOc4jHome    = "";

my $agentMode       = &SecureUtil::getAgentMode();
my $emAgentHome     = "";
my $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";
 $redirectStderr = "";
}
else
{
 $IS_WINDOWS="FALSE";
}

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 "dbconsole")
    {
       $emAgentHome     = &SecureUtil::getEMHome($agentMode);
       $securelog       = "$emAgentHome/sysman/log/secure.log";
       SecureUtil::setLogFile($securelog);
       secureDBConsoleNew($rargs);
       $result = $EMCTL_DONE;
    }
    elsif($rargs->[1] eq "sync")
    {
       $emAgentHome     = &SecureUtil::getEMHome($agentMode);
       $securelog       = "$emAgentHome/sysman/log/secure.log";
       SecureUtil::setLogFile($securelog);
       secureSync();
       $result = $EMCTL_DONE;
    }
    elsif ($rargs->[1] eq "setpwd")
    {
       $emAgentHome     = &SecureUtil::getEMHome($agentMode);
       $securelog       = "$emAgentHome/sysman/log/secure.log";
       SecureUtil::setLogFile($securelog);
       secureSetPwd ($rargs);
       $result = $EMCTL_DONE;
    }
    elsif ($rargs->[1] eq "status")
    {
       $emAgentHome     = &SecureUtil::getEMHome($agentMode);
       $securelog       = "$emAgentHome/sysman/log/secure.log";
       SecureUtil::setLogFile($securelog);
       secureStatus ("dbconsole");
       $result = $EMCTL_DONE;
    }
    else
    {
       $result = $EMCTL_UNK_CMD;
    }
  }
  elsif ($argCount >= 2  && $rargs->[0] eq "unsecure")
  {
    if($rargs->[1] eq "dbconsole")
    {
       $emAgentHome     = &SecureUtil::getEMHome($agentMode);
       $securelog       = "$emAgentHome/sysman/log/secure.log";
       SecureUtil::setLogFile($securelog);
       unsecure($rargs);
       $result = $EMCTL_DONE;
    }
    else
    {
       $result = $EMCTL_UNK_CMD;
    }
  }
  else
  {
    $result = $EMCTL_UNK_CMD;
  }
  return $result;
}

sub usage
{
  print "Secure DBConsole Usage : \n";
  print "emctl secure dbconsole -sysman_pwd <sysman password> [-passwd_file <abs file loc>]\n";
  print "\t[-host <slb hostname>] [-sid <service name>] [-reset] [-secure_port <secure_port>]\n";
  print "\t[-cipher_suites <comma_separated_list_of_suites>] [-sign_alg <md5|sha1|sha256|sha384|sha512>]\n";
  print "\t[-root_dc <root_dc>] [-root_country <root_country>] [-root_state <root_state>] [-root_loc <root_loc>]\n";
  print "\t[-root_org <root_org>] [-root_unit <root_unit>] [-root_email <root_email>]\n";
  print "\t[-wallet <wallet loc>] [-wallet_pwd <wallet pwd>] [-trust_certs_loc <certs loc>]\n";
  print "emctl secure status dbconsole\n";
# Keep the following message conceal from the user, please! (Refer to the bug 6157677)
#  print "emctl unsecure dbconsole\n";
}


sub secureDBConsoleNew
{
  my $sysman_pwd = "";
  my $sysman_pwd_str = "";
  my $host = "";
  my $sid = "";
  my $port = "";
  my $cipher_suites = "";
  my $signAlg = "";
  my $resetFlag = "";
  my $root_dc = "";
  my $root_country = "";
  my $root_state = "";
  my $root_loc = "";
  my $root_org = "";
  my $root_unit = "";
  my $root_email = "";
  my $wallet = "";
  my $wallet_pwd = "";
  my $wallet_pwd_str = "";
  my $trust_certs_loc = "";
  my $key_strength;
  my $emConsoleMode = "DBCONSOLE";
  my $javaStr = "";
  my $jitOpts = "";
  my $classPath = "";
  my $emHome = "";
  my $oc4jHome = "";
  my $stopStatus = "";
  my $stopStatusAgent = "";
  my $isRemoteNode = "false";

  GetOptions("sysman_pwd:s"=>\$sysman_pwd,
             "host:s"=>\$host,
             "sid:s"=>\$sid,
             "secure_port:s"=>\$port,
             "cipher_suites:s"=>\$cipher_suites,
             "sign_alg:s"=>\$signAlg,
             "reset"=>\$resetFlag,
             "wallet:s"=>\$wallet,
             "wallet_pwd:s"=>\$wallet_pwd,
             "trust_certs_loc:s"=>\$trust_certs_loc,
             "root_dc:s"=>\$root_dc,
             "root_country:s"=>\$root_country,
             "root_state:s"=>\$root_state,
             "root_loc:s"=>\$root_loc,
             "root_org:s"=>\$root_org,
             "root_unit:s"=>\$root_unit,
             "root_email:s"=>\$root_email,
             "key_strength:s"=>\$key_strength);
  
  my $rc = $EMCTL_UNK_CMD;

  if($sysman_pwd)
  {
    $sysman_pwd_str = $sysman_pwd;
  }
  else
  {
    $sysman_pwd_str = &EmctlCommon::promptUserPasswd("Please enter repository password: ");
    if($sysman_pwd_str eq '')
    {
        # User hit enter without typing anything
        die "Password not entered.\n";
    }
  }

  if($wallet)
  {
    if($wallet_pwd)
    {
      $wallet_pwd_str = $wallet_pwd;
    }
    else
    {
      $wallet_pwd_str = &EmctlCommon::promptUserPasswd("Please enter wallet password: ");
      if($wallet_pwd_str eq '')
      {
        # User hit enter without typing anything
        die "Password not entered.\n";
      }
    }
  }

  if ( ($host ne "") && ($sid ne "") )
  {
      #If both host and sid are provided, consider it as remote node
      #Additionally compare with local hostname to ensure that host specified is not localhost
      my $localhost = &EmctlCommon::getLocalHostName();
      if($host ne $localhost)
      {
        $isRemoteNode = "true";
      }
  }

  # Stop DBConsole if required; do not stop local node while securing remote node
  if($isRemoteNode eq "false")
  {
  $stopStatus = stopDBConsole($securelog);
  if ($stopStatus eq 0 or $stopStatus eq 1)
  {
    $stopStatusAgent = stopAgent($securelog);
    if ($stopStatusAgent eq 0 or $stopStatusAgent eq 1)
    {
       SecureUtil::USERINFO ("Securing dbconsole...   Started.\n");
    }
    else
    {
       SecureUtil::USERINFO ("Securing dbconsole...   Aborted.\n");
       exit 2;
    }
  }
  else
  {
    SecureUtil::USERINFO ("Securing dbconsole...   Aborted.\n");
    exit 2;
  }
  }


  $classPath = SecureUtil::getConsoleClassPath();

  if ( ($host ne "") && ($sid ne "") )
  {
      # If both host and sid are provide, consider it as remote node
      $emHome      = $ORACLE_HOME."/".$host."_".$sid;
      $oc4jHome    = $ORACLE_HOME."/oc4j/j2ee/OC4J_DBConsole_".$host."_".$sid;
  }
  else
  {
      # If host is provided without sid or no host is provided, default host to local host
      # If host is not provided, default to localhost
      $host = &EmctlCommon::getLocalHostName();
      SecureUtil::DEBUG ("Defaulting hostname to  $host");
      $emHome    = &SecureUtil::getEMHome($emConsoleMode);
      $oc4jHome  = &SecureUtil::getOC4JHome($emConsoleMode);

      if ($sid eq "")
      {
         $sid = $ORACLE_SID;
      }
  }

  $classPath = "$ORACLE_HOME/oc4j/jdbc/lib/ojdbc5dms.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-mapping.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-translation.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-net-ee.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-utility.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-collation.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-net.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-internal.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-servlet.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-lcsd.jar".
	       "$cpSep$ORACLE_HOME/oc4j/jdbc/lib/orai18n-tools.jar".
               "$cpSep$ORACLE_HOME/oc4j/lib/dms.jar".
               "$cpSep$ORACLE_HOME/jlib/uix2.jar".
               "$cpSep$ORACLE_HOME/jlib/share.jar".
               "$cpSep$ORACLE_HOME/jlib/ojmisc.jar".
               "$cpSep$ORACLE_HOME/lib/xmlparserv2.jar".
               "$cpSep$ORACLE_HOME/sysman/jlib/emagentSDK.jar".
               "$cpSep$ORACLE_HOME/sysman/jlib/emagentRT.jar".
               "$cpSep$ORACLE_HOME/oc4j/j2ee/home/lib/http_client.jar".
               "$cpSep$ORACLE_HOME/sysman/jlib/log4j-core.jar".
               "$cpSep$ORACLE_HOME/sysman/jlib/emCORE.jar".
               "$cpSep$ORACLE_HOME/sysman/jlib/emDB.jar".
               "$cpSep$ORACLE_HOME/jlib/osdt_core.jar" .
               "$cpSep$ORACLE_HOME/jlib/osdt_cert.jar" .
               "$cpSep$ORACLE_HOME/jlib/oraclepki.jar" ;

  #Bug 6345466 - Securing is failing intermittently on AIX. Turned out to be issue with IBM JDK on AIX
  #IBM JDK team suggested to pass -Xjit:disableTreeSimplification option as a workaround
  #This file can be debranched once SR6 release of IBM JVM is used
  if($OSNAME eq "aix")
  {
    $jitOpts = "-Xjit:disableTreeSimplification";
  }

  # 19788842 :
  #   If EmctlCommon.pm doesn't define $EM_SOL_JAVA, but this file uses it, 
  #   emctl command executions would hit 19788842 as this file contains "use strict" stmt.
  #   Fix is to specify explicit package name for $EM_SOL_JAVA in this file 
  #   -- i.e. replace $EM_SOL_JAVA with $EmctlCommon::EM_SOL_JAVA
  $javaStr = "$JAVA_HOME/bin/java $EmctlCommon::EM_SOL_JAVA $jitOpts ".
             "-cp $classPath ".
             "-DORACLE_HOME=$ORACLE_HOME ".
             "-DEMSTATE=$emHome ".
             "-DORACLE_SID=$ORACLE_SID ".
             "-DOC4J_HOME=$oc4jHome ".
             "-Ddebug=$debug ".
             "oracle.sysman.emctl.secure.dbc.SecureDBConsoleCmds -action secure ";

  if ($host)
  {
      $javaStr = $javaStr . " -host $host ";
  }
  else
  {
     # If host is not provided, default to localhost
     $host = &EmctlCommon::getLocalHostName();
     SecureUtil::DEBUG ("Defaulting hostname to  $host");
     $javaStr = $javaStr . " -host $host ";
  }
  if ($sid)
  {
      $javaStr = $javaStr . " -sid $sid ";
  }
  if($key_strength)
  {
      $javaStr = $javaStr . " -key_strength $key_strength";
  }
  if ($port)
  {
      $javaStr = $javaStr . " -secure_port $port ";
  }
  if($cipher_suites)
  {
      $javaStr = $javaStr . " -cipher_suites $cipher_suites ";
  }
  if($signAlg)
  {
      $javaStr = $javaStr . " -sign_alg $signAlg ";
  }
  if ($resetFlag)
  {
      $javaStr = $javaStr . " -reset ";
  }
  if ($root_dc)
  {
      $javaStr = $javaStr . " -root_dc $root_dc ";
  }
  if ($root_country)
  {
      $javaStr = $javaStr . " -root_country $root_country ";
  }
  if ($root_state)
  {
      $javaStr = $javaStr . " -root_state $root_state ";
  }
  if ($root_loc)
  {
      $javaStr = $javaStr . " -root_loc $root_loc ";
  }
  if ($root_org)
  {
      $javaStr = $javaStr . " -root_org $root_org ";
  }
  if ($root_unit)
  {
      $javaStr = $javaStr . " -root_unit $root_unit ";
  }
  if ($root_email)
  {
      $javaStr = $javaStr . " -root_email $root_email ";
  }
  if($wallet)
  {
      $javaStr = $javaStr . " -wallet $wallet ";
  }
  if($trust_certs_loc)
  {
      $javaStr = $javaStr . " -trust_certs_loc $trust_certs_loc ";
  }

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

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

  $rc = 0xffff & $?;
  $rc >>= 8;
  if ($rc eq 0 )
  {
    SecureUtil::USERINFO ("Securing dbconsole...   Sucessful.\n");
  }
  elsif ($rc eq 1 )
  {
    SecureUtil::USERINFO ("Securing dbconsole...   Failed.\n");
    SecureUtil::USERINFO ("Invalid Password.\n");
  }
  elsif ($rc eq 2 )
  {
    SecureUtil::USERINFO ("Securing dbconsole...   Failed.\n");
    SecureUtil::USERINFO ("Failed to connect to the repository.\n");
  }
  elsif ($rc eq 3 )
  {
    SecureUtil::USERINFO ("Securing dbconsole...   Failed.\n");
    SecureUtil::USERINFO ("EMKey is misconfigured.\n");
  }
  else
  {
    SecureUtil::USERINFO ("Securing dbconsole...   Failed. Error code = $rc\n");
  }

  if($isRemoteNode eq "false")
  {
  if ($stopStatus eq 0)
  { 
    restartDBConsole($securelog);
    if ($stopStatusAgent eq 0)
    {
       restartAgent($securelog);
    } 
  }
  }

  return $rc;
}

sub unsecure
{
  local (*args)     = @_;
  shift(@args);
  my $argCount      = scalar(@args);
  my $component     = @args->[0];
  my $emConsoleMode = SecureUtil::getConsoleMode; 
  my $emAgentMode   = SecureUtil::getAgentMode;

  if ($component eq "dbconsole")
  {
    if ($emConsoleMode eq "")
    {
      SecureUtil::USERINFO ("Cannot determine Agent type from emd.properties\n");
    }
    else
    {
      if ($emConsoleMode eq "DBCONSOLE")
      {
        SecureUtil::DEBUG ("Unsecure $component\n");
        unsecureDBConsole($emConsoleMode);
      }
      else
      {
        SecureUtil::USERINFO ("You must use emctl unsecure em/iasconsole or agent\n");
        SecureUtil::DEBUG ("$emConsoleMode Console.\n");
      }
    }
  }
  else
  {
    exit $EMCTL_BAD_USAGE;
  }
}


# Copy the following files to the remote node 

#   $OH/<host>_<sid>/sysman/config/emd.properties 
#   $OH/<host>_<sid>/sysman/config/b64LocalCertificate.txt 
#   $OH/<host>_<sid>/sysman/config/b64InternetCertificate.txt 
#   $OH/<host>_<sid>/sysman/config/server/ewallet.p12 
#   $OH/<host>_<sid>/sysman/config/server/repoconn.ora 
#
#   $OH/<host>_<sid>/sysman/config/emoms.properties 
#   $OH/0c4j/j2ee/OC4J_DBConsole_<host>_<sid>/config/http-web-site.xml 
#   $OH/0c4j/j2ee/OC4J_DBConsole_<host>_<sid>/config/server/keystore.test


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

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

  $javaStr = "$JAVA_HOME/bin/java ".
             "-cp $classPath ".
             "-DrepositoryPropertiesFile=$emHome/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 : ", 0);
  }

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

  my $javaStr = "";

  my $emConsoleMode = "DBCONSOLE";
  my $emHome        = &SecureUtil::getEMHome($emConsoleMode);
  my $classPath     = &SecureUtil::getConsoleClassPath($emConsoleMode);
  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=$emHome/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;
}


sub secureStatus
{
  my $component    = $_[0];
  my $propFile;
  my $rc;

  my $ORACLE_HOME     = $ENV{ORACLE_HOME};
  my $JAVA_HOME       = $ENV{JAVA_HOME};
  my $emConsoleMode   = "DBCONSOLE";

  my $emAgentMode     = &SecureUtil::getAgentMode();
  my $emHome          = &SecureUtil::getEMHome($emAgentMode);
  my $emdPropFile     = "$emHome/sysman/config/emd.properties";
  my $securelog       = "$emHome/sysman/log/secure.log";
  SecureUtil::setLogFile($securelog);

  my ($protocol,$machine,$port,$ssl);
  my %agentProps;
  my $rc;

  if ($component eq "dbconsole")
  {
    if (-e $emdPropFile)
    {
       SecureUtil::USERINFO ("Checking the security status of the DBCONSOLE...");
       %agentProps                     = &SecureUtil::parseFile($emdPropFile);
       ($protocol,$machine,$port,$ssl) = &SecureUtil::parseURL($agentProps{"REPOSITORY_URL"});
       SecureUtil::USERINFO ("   Done.\n");

       if ($ssl eq "Y")
       {
         SecureUtil::USERINFO ("DBCONSOLE is secure at HTTPS Port $port.\n");
         $rc = 0;
         SecureUtil::USERINFO ("Checking the security status of the Agent...");
         ($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");
           $rc = 0;
         }
         else
         {
           SecureUtil::USERINFO("Agent is unsecure at HTTP Port $port.\n");
           $rc = 2;
         }
       }
       else
       {
         SecureUtil::USERINFO ("DBCONSOLE is unsecure at HTTP Port $port.\n");
         $rc = 2;
       }
    }
    else
    {
       $rc = 1;
    }
  }
  else
  {
    $rc = 1;
  }
  return $rc;
}


#
#unsecureDBConsole
#
sub unsecureDBConsole
{
   my $rc;
   my (@args)        = @_;
   my $emConsoleMode = "DBCONSOLE";
   my $emHome        = &SecureUtil::getEMHome($emConsoleMode);
   my $oc4jHome      = &SecureUtil::getOC4JHome($emConsoleMode);

   my $stopStatus;
   my $stopStatusAgent;

   #my $file = "$emHome/sysman/config/emd.properties";
   #my $propfile = "$emHome/sysman/config/emd.properties";
   my $agentPropFile = "$emHome/sysman/config/emd.properties";
   my $omsPropFile   = "$emHome/sysman/config/emoms.properties";
   my $emWebSiteFile = "$oc4jHome/config/http-web-site.xml";

   my @omsLines;
   my $omsLineRead;
   my $omsPropFileUpdated = 0;

   SecureUtil::DEBUG ("Using emd.properties file = $agentPropFile\n");
   SecureUtil::DEBUG ("Using emoms.properties file = $omsPropFile\n");
   SecureUtil::DEBUG ("Using http-web-site.xml file = $emWebSiteFile\n");
   
   SecureUtil::USERINFO ("Configuring DBConsole for HTTP...");

   open(AGENTPROPFILE, $agentPropFile) or die "Can not read EMD.PROPERTIES ($agentPropFile)";
   my @emdURLlinesRead = grep /EMD_URL=https:/, <AGENTPROPFILE>;
   close(AGENTPROPFILE) or die "Can not close EMD.PROPERTIES ($agentPropFile)";

   SecureUtil::USERINFO ("   Done.\n");
   
   my $numLinesEMDURL = scalar @emdURLlinesRead;
   if($numLinesEMDURL <= 0)
   {
      SecureUtil::USERINFO ("DBConsole is already unsecured.\n");
   }
   else
   {
      $stopStatus = stopDBConsole($securelog);
      if ($stopStatus eq 0 or $stopStatus eq 1)
      {
         $stopStatusAgent = stopAgent($securelog);
         if ($stopStatusAgent eq 0 or $stopStatusAgent eq 1)
         {
            SecureUtil::USERINFO ("Unsecuring dbconsole...   Started.\n");
         }
         else
         {
            SecureUtil::USERINFO ("Unsecuring dbconsole...   Aborted.\n");
            exit 2;
         }
      }
      else
      {
         SecureUtil::USERINFO ("Unsecuring dbconsole...   Aborted.\n");
         exit 2;
      }

      SecureUtil::DEBUG ("Changing secure url to unsecure url.\n");

      my $emd_check_url = 0;
      my $rep_check_url = 0;
      my $sec_check = 0;
      my $verify_em_upload_http_url = "";

      open(SECINFO, $emWebSiteFile) or die "Can not read $emWebSiteFile";
      my @seclines = <SECINFO>;
      close(SECINFO)|| die;
      # Walk the lines, and write to new file
      open (SECFILE, ">$emWebSiteFile.$$") || die "Cannot write to $emWebSiteFile.$$\n";
      foreach my $seclineRead (@seclines)
      {
         if($seclineRead =~ /<web-site.*port/)
         {
            if($seclineRead =~ /secure="true"/i)
            {
               $seclineRead =~ s/(TRUE|true)/false/;
               $sec_check = 1;
               SecureUtil::DEBUG ("Configuring http-web-site.xml file.\n");
            }
            if($seclineRead =~ /secure="false"/i)
            {
               $sec_check = 1;
            }
         }
         print SECFILE "$seclineRead";
      }
      close(SECFILE)|| die;

      if ($sec_check == 1)
      {
         # Update the agent configuration 
         open(AGENTPROPFILE, $agentPropFile);
         my @emdlines = <AGENTPROPFILE>;
         close(AGENTPROPFILE) || die;
         open (AGENTPROPFILE, ">$agentPropFile.$$") || die "Cannot write to $agentPropFile.$$\n";
         # Walk the lines, and write to new file
         foreach my $emdlineRead (@emdlines)
         {
             if($emdlineRead =~ /REPOSITORY_URL=https:/)
             {
                $emdlineRead =~ s/https\:/http\:/;
                $verify_em_upload_http_url = $emdlineRead;
                chomp($verify_em_upload_http_url);
                $verify_em_upload_http_url =~ s/REPOSITORY_URL=http\:/http\:/;
                $rep_check_url = 1;
             }
             if($emdlineRead =~ /EMD_URL=https:/)
             {
                SecureUtil::DEBUG ("Check EMD_URL = $emdlineRead\n");
                $emdlineRead =~ s/https\:/http\:/;
                $emd_check_url = 1;
             }
             print AGENTPROPFILE "$emdlineRead";
         }
         close (AGENTPROPFILE) || die;

         # Update the OMS configuration 
         open(OMSPROPFILE, $omsPropFile);
         @omsLines = <OMSPROPFILE>;
         close(OMSPROPFILE) || die;

         open (OMSPROPFILE, ">$omsPropFile.$$") || die "Cannot write to $omsPropFile.$$\n";
         # Walk the lines, and write to a new file with updated props
         SecureUtil::DEBUG ("Modifying OMS props");
         foreach my $omsLineRead (@omsLines)
         {
             if($omsLineRead =~ /EMD_URL=https/)
             {
                SecureUtil::DEBUG ("Line matched = $omsLineRead");
                $omsLineRead =~ s/https\\:/http\\:/;
                SecureUtil::DEBUG ("EMD_URL line updated to $omsLineRead");
                $omsPropFileUpdated = 1;
             }
             if($omsLineRead =~ /oracle.sysman.emSDK.svlt.ConsoleServerHTTPSPort=/)
             {
                $omsLineRead = "oracle.sysman.emSDK.svlt.ConsoleServerHTTPSPort=-1\n";
                SecureUtil::DEBUG ("Console port property updated");
                $omsPropFileUpdated = 1;
             }
             print OMSPROPFILE "$omsLineRead";
         }
         close (OMSPROPFILE) || die "Cannot close file $omsPropFile.$$\n";

         if ($omsPropFileUpdated == 1)
         {
             SecureUtil::CP ("$omsPropFile", "$omsPropFile.bak.$$");
             SecureUtil::CP ("$omsPropFile.$$", "$omsPropFile");
         }
         SecureUtil::RM ("$omsPropFile.$$");

         if ($rep_check_url == 1 and $emd_check_url == 1) 
         {
             SecureUtil::CP ("$agentPropFile", "$agentPropFile.bak.$$");
             SecureUtil::CP ("$agentPropFile.$$", $agentPropFile);
             SecureUtil::RM ("$agentPropFile.$$");
             SecureUtil::CP ("$emWebSiteFile", "$emWebSiteFile.bak.$$");
             SecureUtil::CP ("$emWebSiteFile.$$", $emWebSiteFile);
             SecureUtil::RM ("$emWebSiteFile.$$");
             SecureUtil::USERINFO ("DBConsole is now unsecured...  Done.\n");
             SecureUtil::USERINFO ("Unsecuring dbconsole...  Sucessful.\n");
             $rc = 0;
         }
         else
         {
             SecureUtil::RM ("$agentPropFile.$$");
             SecureUtil::RM ("$emWebSiteFile.$$");
             SecureUtil::USERINFO ("Unsecuring dbconsole...   Failed.\n");
             $rc = 1;
         }
      }
   }

  if ($stopStatus eq 0)
  {
    restartDBConsole($securelog);
    if ($stopStatusAgent eq 0)
    {
       restartAgent($securelog);
    }
  }

  return $rc;
}

sub stopDBConsole
{
  my $rc;
  my $securelog = $_[0];
  my $redirectStderr    = "2>&1";

  my $dbStopStr    = "$ORACLE_HOME/bin/emctl stop dbconsole >> $securelog $redirectStderr";
  my $dbStartStr   = "$ORACLE_HOME/bin/emctl start dbconsole >> $securelog $redirectStderr";
  my $dbStatusStr  = "$ORACLE_HOME/bin/emctl status dbconsole >> $securelog $redirectStderr";

  $rc = getDBConsoleStatus();
  if ($rc eq 0)
  {
    system($dbStopStr);
    $rc = getDBConsoleStatus();
    if ($rc eq 0)
    {
      SecureUtil::USERINFO ("Failed to stop dbconsole...\n");
      exit 2;
    }
    elsif ($rc eq 2)
    {
      SecureUtil::USERINFO ("DBCONSOLE successfully stopped...   Done.\n");
      return 0;
    }
    else
    {
      my $tries=30;
      while( $tries gt 0 )
      {
        sleep 1;
        $rc = getDBConsoleStatus();
        if ($rc ne 2)
        {
          last;
        }
        $tries = $tries-1;
        print ".";
      }
      $rc = getDBConsoleStatus();
      if ($rc eq 2)
      { 
        SecureUtil::USERINFO ("DBCONSOLE successfully stopped...   Done.\n");
        return 0;
      }
      else
      {
        SecureUtil::USERINFO ("Failed to stop dbconsole...\n");
        SecureUtil::DEBUG ("Error: $rc...\n");       
        exit 2;
      }
    }
  }
  elsif ($rc eq 2)
  {
    SecureUtil::USERINFO ("DBCONSOLE already stopped...   Done.\n");
    return 1;
  }
  else
  {
    my $tries=30;
    while( $tries gt 0 )
    {
      sleep 1;
      $rc = getDBConsoleStatus();
      if ($rc ne 2)
      {
        last;
      }
      $tries = $tries-1;
      print ".";
    }
    $rc = getDBConsoleStatus();
    if ($rc eq 2)
    { 
      SecureUtil::USERINFO ("DBCONSOLE successfully stopped...   Done.\n");
      return 0;
    }
    else
    {
      SecureUtil::USERINFO ("Failed to stop dbconsole...\n");
      SecureUtil::DEBUG ("Error: $rc...\n");
      exit 2;
    }
  }
}


sub restartDBConsole
{
  my $rc;
  my $securelog = $_[0];
  my $redirectStderr    = "2>&1";

  my $dbStopStr    = "$ORACLE_HOME/bin/emctl stop dbconsole >> $securelog $redirectStderr";
  my $dbStartStr   = "$ORACLE_HOME/bin/emctl start dbconsole >> $securelog $redirectStderr";
  my $dbStatusStr  = "$ORACLE_HOME/bin/emctl status dbconsole >> $securelog $redirectStderr";

  system($dbStartStr);
  $rc = getDBConsoleStatus();
  if ($rc eq 0)
  {
    SecureUtil::USERINFO ("DBCONSOLE successfully restarted...   Done.\n");
    return 0;
  }
  elsif ($rc eq 2)
  {
    SecureUtil::USERINFO ("Failed to restart dbconsole...\n");
    exit 2;
  }
  else
  {
    my $tries=30;
    while( $tries gt 0 )
    {
      sleep 1;
      $rc = getDBConsoleStatus();
      if ($rc ne 0)
      {
        last;
      }
      $tries = $tries-1;
      print ".";
    }
    $rc = getDBConsoleStatus();
    if ($rc eq 0)
    { 
      SecureUtil::USERINFO ("DBCONSOLE successfully restarted...   Done.\n");
      return 0;
    }
    else
    {
      SecureUtil::USERINFO ("Failed to restart dbconsole...\n");
      SecureUtil::DEBUG ("Error: $rc...\n");       
      exit 2;
    }
  }
}


sub stopAgent
{
  my $rc;
  my $securelog       = $_[0];
  my $agentStatusStr  = "$EMDROOT/bin/emdctl status agent 1>> $securelog 2>> $devNull";
  my $agentStopStr    = "$ORACLE_HOME/bin/emctl stop agent 1>> $securelog 2>> $devNull";
  my $agentStartStr   = "$ORACLE_HOME/bin/emctl start agent 1>> $securelog 2>> $devNull";

  $rc = 0xffff & system($agentStatusStr);
  $rc >>= 8;
  if ($rc eq 3 or $rc eq 4)
  {
    system($agentStopStr);
    my $tries=30;
    while( $tries gt 0 )
    {
      sleep 1;
      $rc = 0xffff & system($agentStatusStr);
      $rc >>= 8;
      if ($rc lt 2)
      {
         last;
      }
      $tries = $tries-1;
      print ".";
    }
    $rc = 0xffff & system($agentStatusStr);
    $rc >>= 8;
    if ($rc eq 3 or $rc eq 4)
    {
      SecureUtil::USERINFO ("Failed to stop agent...\n");
      exit 2;
    }
    elsif ($rc eq 1)
    {
      SecureUtil::USERINFO ("Agent successfully stopped...   Done.\n");
      return 0;
    }
    else
    {
      SecureUtil::USERINFO ("Failed to stop agent...\n");
      SecureUtil::DEBUG ("Error: $rc...\n");
      exit 2;
    }
  }
  elsif ($rc eq 1)
  {
    SecureUtil::USERINFO ("Agent is already stopped...   Done.\n");
    return 1;
  }
  else
  {
    SecureUtil::USERINFO ("Failed to stop agent...\n");
    SecureUtil::DEBUG ("Error: $rc...\n");
    exit 2;
  }
}


sub restartAgent
{
  my $rc;
  my $securelog       = $_[0];
  my $agentStatusStr  = "$EMDROOT/bin/emdctl status agent 1>> $securelog 2>> $devNull";
  my $agentStopStr    = "$ORACLE_HOME/bin/emctl stop agent 1>> $securelog 2>> $devNull";
  my $agentStartStr   = "$ORACLE_HOME/bin/emctl start agent 1>> $securelog 2>> $devNull";

  system($agentStartStr);
  $rc = 0xffff & system($agentStatusStr);
  $rc >>= 8;
  if ($rc eq 3)
  {
    SecureUtil::USERINFO ("Agent successfully restarted...   Done.\n");
    return 0;
  }
  elsif ($rc eq 1)
  {
    SecureUtil::USERINFO ("Failed to restart agent...\n");
    exit 2;
  }
  elsif ($rc eq 4)
  {
    my $tries=30;
    while( $tries gt 0 )
    {
      sleep 1;
      $rc = 0xffff & system($agentStatusStr);
      $rc >>= 8;
      if ($rc ne 3)
      {
         last;
      }
      $tries = $tries-1;
      print ".";
    }
    $rc = 0xffff & system($agentStatusStr);
    $rc >>= 8;
    if ($rc eq 3)
    {
      SecureUtil::USERINFO ("Agent successfully restarted...   Done.\n");
      return 0;
    }
    else
    {
      SecureUtil::USERINFO ("Failed to restart agent...\n");
      SecureUtil::DEBUG ("Error: $rc...\n");
      exit 2;
    }
  }
  else
  {
    SecureUtil::USERINFO ("Failed to restart agent...\n");
    SecureUtil::DEBUG ("Error: $rc...\n");
    exit 2;
  }
}


sub getDBConsoleStatus
{
  my $console = new DBConsole();
  my $rc = 2;
  if ( -e "$PID_FILE" )
  {
      my($PID);
      open(PIDFILE, "<$PID_FILE");
      while(<PIDFILE>)
      {
          $PID = $_;
      }
      close(PIDFILE);
      chomp($PID);

      $console->Initialize($PID, time(), $DEBUG_ENABLED);
      $rc = $console->status();

      if($rc == $STATUS_NO_SUCH_PROCESS)
      {
          $rc = 2;
      }
      elsif($rc == $STATUS_PROCESS_OK)
      {
          $rc = 0;
      }
      else
      {
          $rc = 1;
      }
  }
  return $rc
}


1;
