#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2005,2007 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)67   1.4   src/csm/install/waitForRsct.perl, setup, csm_rfish, rfishs001b 12/20/06 00:04:18

use strict;
use locale;
BEGIN
  {
	# this enables us to redirect where it looks for other CSM files during development
	$::csmroot = $ENV{'CSM_ROOT'} ? $ENV{'CSM_ROOT'} : '/opt/csm';
	$::csmpm = "$::csmroot/pm";
	$::csmbin = "$::csmroot/bin";
  }
use lib $::csmpm;
require NodeUtils;
use Getopt::Std;

$ENV{'CT_MANAGEMENT_SCOPE'}=1;

# Parse the cmd line args and check them
if (! getopts('vt:') ) { &usage; }
if(!defined $::opt_t){ $::opt_t=180; } #wait 180 seconds by default
if(defined $::opt_v){ $::VERBOSE=1; } #verbose

if(scalar @ARGV > 1){
  print "waitForRsct can only wait for 1 resource manager at a time\n";
}

my $resMan="";
if(scalar @ARGV ==1){
  $resMan = $ARGV[0];
}
$::TimeSlept=0;

&waitForRSCT();

if($resMan ne ""){
  &waitForRM($resMan);
}

sub waitForRSCT{
  while(1){
    # this should tell us if the RMC subsystem is available
    my @output = NodeUtils->runcmd("/usr/bin/lsrsrc", -1);
    if(!$::RUNCMD_RC){
      # The RMC subsystem has responded.
      last;
    }
	else {
      &countSleep(2);
    }
  }
  return 0;
}


sub waitForRM{
  my $resMan = $_[0];

  # The ERRM resource mgr is slow in starting.  Wait until it starts before
  # continuing or else it can cause problems later on
  while(1)
    {
      if (NodeUtils->isRMrunning($resMan))
	{
	  my $ctrmc_up = 0;
	  #now check if ctrmc is up 
	  my @output = NodeUtils->runcmd("LANG=C /usr/bin/lssrc -s ctrmc", -1);
	  if(!$::RUNCMD_RC){
	    my ($subsys, $group, $pid, $status) = split(' ', $output[1]);
	    if (defined($status) && $status eq 'active'){
	      $ctrmc_up =1;
	    }
	    }
	  if($ctrmc_up==1){
	    last;
	  }
	}
      &countSleep(2);
    }
}

sub countSleep{
  my $numSec = $_[0];
  my $i = 0;
  while ($i < $numSec){
	if($::TimeSlept >= $::opt_t){
	  print "Timed out waiting for RSCT.\n";
	  exit 2;
	}
	sleep 1;
	$i++;
	$::TimeSlept++;
  }
}

