#!/usr/local/bin/perl
# 
# $Header: emdb/sysman/admin/scripts/rac/db_inst_names.pl /st_emdbsa_11.2/1 2009/03/30 20:50:25 shasingh Exp $
#
# db_inst_names.pl
# 
# Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. 
#
#    NAME
#      db_inst_names.pl - <one-line expansion of the name>
#
#    DESCRIPTION
#      <short description of component this file declares/defines>
#
#    NOTES
#      <other useful comments, qualifications, etc.>
#
#    MODIFIED   (MM/DD/YY)
#    shasingh    03/24/09 - evaluate database current instance names
#    shasingh    03/24/09 - Creation
# 

use strict;
require "semd_common.pl";

my $LOG_CATEGORY = "DATABASE_INSTANCE_LISTS: ";

# save ORACLE_HOME and restore it back in END
my $oldOH = $ENV{ORACLE_HOME} if $ENV{ORACLE_HOME};
unset_lib_path_env();

my %stdinArgs = get_stdinvars();
my $dbname = $stdinArgs{EM_TARGET_DBNAME} if $stdinArgs{EM_TARGET_DBNAME};
my $oraclehome = $stdinArgs{EM_TARGET_ORACLE_HOME} if $stdinArgs{EM_TARGET_ORACLE_HOME};

my $instance_list = getDBInstanceNames($oraclehome,$dbname); 

print "em_result=$instance_list\n";
 
exit 0;

END
{
  $ENV{ORACLE_HOME} = $oldOH if $oldOH;
}

# Evaluate the database current instance names
sub getDBInstanceNames 
{
 my ($oh, $db_name ) = @_;
 
 my $cmd = "$oh/bin/srvctl status database -d $db_name -S 1";
 my ( $err, $output ) = executeCommand( $cmd, $oh );
 EMD_PERL_DEBUG("$LOG_CATEGORY getDBInstanceNames-> $cmd returned (err=$err, output=$output)");
 my @instance_name_array = ();
 if($err eq "")
 {
  my @lns = split /\n/, $output;
  for my $ln (@lns)
  {
   if ($ln =~ /dbunique_name\s*=\s*\{\s*$db_name\s*\}.*?inst_name\s*=\s*\{(.*?)\}/i)
   {
   	push(@instance_name_array, $1);
    EMD_PERL_DEBUG("$LOG_CATEGORY getDBInstanceNames->Instance name: $1");
   }
  }
 }
  
 my $instance_names = join (",", @instance_name_array);
   
 ($instance_names);
}


# execute the supplied command
sub executeCommand
{
 my ( $cmd, $oh ) = @_;
 $ENV{ORACLE_HOME} = $oh;
 my $err    = "";
 my $output = "";
 if ( open( CMDOUTPUT, "$cmd 2>&1 |" )) 
 {
  my @outputs = <CMDOUTPUT>;
  $output = join "", @outputs;
  if ( !close(CMDOUTPUT) ) 
  {
   # close error
   if ( $output ne "" ) 
   {
    $err    = "\"${cmd}\" returned: \"" . $output . "\"";
    $output = "";
   }
   else
   {
    $err = "bad \"$cmd\": $! $?";
   }
  }
 }
 else
 {
  # open error
  $err = "cannot execute \"$cmd\": $!";
 }

 EMD_PERL_ERROR("executeCommand: $cmd: $err") if ( $err ne "" );
 ( $err, $output );
}

# unset the *LD_* env variable for proper function of srvctl
sub unset_lib_path_env 
{
 delete $ENV{LD_LIBRARY_PATH};
 delete $ENV{SHLIB_PATH};
 delete $ENV{LIBPATH};
 delete $ENV{DYLD_LIBRARY_PATH};
}
