#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2001,2019 
# 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 
#
# sccsid = "@(#)11   1.17   src/rsct/cfg_access/cfgmgr/ct_hags_info.perl, cfg.access, rsct_rady, rady2035a 11/12/15 16:43:43"

# Usage: ct_hags_info [-l] [-w]
#    -l  to get the data from the local repository (no-use)
#    -w  to set the data to the repository (input from stdin)
#    -p  to get non-preferred node list
#    -P  to get preferred node list
# This will give the hags subsystem information
#       REALM		CLUSTER
#	PORT 		<port number>
#	LOGFILELEN 	<logfile-len>		# optional
#	LOGDIRSIZE	<dir size in KB>	# optional
#

use Getopt::Std;

# set peer domain scope
$ENV{CT_MANAGEMENT_SCOPE} = 2;

my %opts = ();
&getopts(':lwpP',\%opts);

if (defined($opts{p}))
{
        # defect 167390: Get non-preferred node list.

        my ($domainName);

        $domainName = `/opt/rsct/bin/ct_clusterinfo -c`;
        chomp($domainName);

	$ENV{'CT_SR_FS_HOME'} = "/var/ct/$domainName/registry/local_tree";

	open PEER_NODES, "lssrtbl-api -s /IBM/PeerNode/Resources::::IsPreferredGSGL::NodeList |" or die sprintf("Line %u: Could not pipe lssrtbl-api\n", __LINE__);

	while (<PEER_NODES>)
	{
		chomp;

		($isPreferredGSGL, $nodeList) = split /::/;

		if ("1" != $isPreferredGSGL)
		{
			$nodeList =~ s/{([0-9]*)}/$1/;
			print "$nodeList\n";
		}
	}

	close PEER_NODES;

	exit 0;
}

if (defined($opts{P}))
{
        # defect 150401: use ct_clusterinfo -c will be faster
        # and so replace this lsclcfg -x -D with ct_clusterinfo -c
	#$_ = `lsclcfg -x -D' '`;

	#my ($domainName, $domainId) = split;

        my ($domainName);

        $domainName = `/opt/rsct/bin/ct_clusterinfo -c`;
        chomp($domainName);

	$ENV{'CT_SR_FS_HOME'} = "/var/ct/$domainName/registry/local_tree";

	open PEER_NODES, "lssrtbl-api -s /IBM/PeerNode/Resources::::IsPreferredGSGL::NodeList |" or die sprintf("Line %u: Could not pipe lssrtbl-api\n", __LINE__);

	while (<PEER_NODES>)
	{
		chomp;

		($isPreferredGSGL, $nodeList) = split /::/;

		if ("1" == $isPreferredGSGL)
		{
			$nodeList =~ s/{([0-9]*)}/$1/;
			print "$nodeList\n";
		}
	}

	close PEER_NODES;

	exit 0;
}

my $mmsetting=(defined($opts{w}) ? 1 : 0);

$RSCTBIN="/opt/rsct/bin";
$SUBSYS_PREFIX = "cthags";
($dir,$progname) = $0 =~ /(.*\/)?(.*)/; # get basename of $0

# ValidKeys: list of all acceptable keys (either canset or not).
# In other words, the input keys must be in the list.
# Otherwise, an error will be issued.

$NON_SETTABLE = 0;
$SETTABLE = 1;

%ValidKeys = (
    "ENVIRONMENT"       => $NON_SETTABLE,
    "START_AT_BOOT"      => $NON_SETTABLE,
    "RESTART_BY_SRC"      => $NON_SETTABLE,
    "REALM"             => $NON_SETTABLE,
    "PORT"              => $NON_SETTABLE,
    "LOGFILELEN"        => $SETTABLE,
    "LOGDIRSIZE"        => $SETTABLE
);

# main starts here
if($mmsetting) {
    #write the data to the repository
    &set_data_to_repository();
} else {
    my $outcnt = &get_data_from_repository();
    if($outcnt == 0) {
	# No output
	&print_errmsg("EMSG107 $progname");
	exit(1);
    }
}
exit(0);

#-------- functions -----------------------------------
# print_dbgmsg(list)
sub print_dbgmsg
{
  my @args = @_;
  if(!defined($ccal_log_inited)) {
	my $outfile = $ENV{"HA_CCAL_LOG"};
	$ccal_log_inited = 0;
	if(defined($outfile) && open(LOGOUT, ">>$outfile")) {
	    $ccal_log_inited = 1;
	    select LOGOUT;
	    $| = 1; # unbuffered
	    select STDOUT;
	}
  }
  if($ccal_log_inited) {
	my $dstr = scalar(localtime);
	my $msg = "$dstr $progname: " . join(" ", @args);
	print LOGOUT $msg, "\n" ;
  }
}

sub print_errmsg
{
   $msgcmd = "$RSCTBIN/hadspmsg cfgaccess ha_com.cat ". join(" ",@_);
   system($msgcmd);
}
#-----------------------------------------------------

# GET DATA from the repository
sub get_data_from_repository
{
   # print REALM
   print "REALM         CLUSTER\n";

   # show the environment and AutoStart flags
   print "ENVIRONMENT    cfgmgr\n";
   print "START_AT_BOOT  0\n";

   if( ! -e "$RSCTBIN/ct_clusterinfo" ) {
   	# No ${RSCTBIN}/ct_clusterinfo found.
        &print_errmsg("EMSG104 $progname ${RSCTBIN}/ct_clusterinfo");
	exit(1);
   }

   # Is CAA configured or not (even if it is being migrated)
   $CLSTENV = `$RSCTBIN/ct_clusterinfo -r -M`;
   chomp($CLSTENV);
   if( defined($CLSTENV) && $CLSTENV eq "CAA" ) {
	print "RESTART_BY_SRC 1\n";
   } else {
	print "RESTART_BY_SRC 0\n";
   }

   # cluster name
   $CLSTNAME = `$RSCTBIN/ct_clusterinfo -c`;
   chomp($CLSTNAME);
   if( !defined($CLSTNAME) || $CLSTNAME eq "" ) {
	# No cluster name found.;
        &print_errmsg("EMSG105 $progname $CLSTNAME");
	exit(1);
   }

   $GSLogSize = -1;
   $GSMaxDirSize = -1;

   # Copy from the rsct.params
   $RSCTPARAMS = $ENV{"CT_RSCT_PARAMS"};
   if( !defined($RSCTPARAMS) ) {
	$RSCTPARAMS = "/var/ct/$CLSTNAME/cfg/rsct.params";
   }
   if(open(PARMFP, "<$RSCTPARAMS")) {
	while( <PARMFP> ) {
	    chomp($_);       # Remove trailing '\n'
	    # 2 simple s/// are faster than one complex s///.
	    s/^[ \t\n]*//;   # Remove possible leading spaces
	    s/#.*$//;       # Remove possible trailing comments
	    ($keyword, $keyvalue) = split(/=/, $_, 2);
	    if($keyword =~ "GSLogSize") {
		$GSLogSize = $keyvalue;
	    } elsif($keyword =~ "GSMaxDirSize") {
		$GSMaxDirSize = $keyvalue;
	    }
	}
	close PARAMFP;
   }

   if(defined($PORT) && ($PORT != 0)) {
	print "PORT         $PORT\n";
   }

   print "LOGFILELEN    $GSLogSize\n";
   print "LOGDIRSIZE    $GSMaxDirSize\n";

   return 4;	# 4 lines of output
}


# SET DATA to the repository 
sub set_data_to_repository
{
   my $count = 0;
   my %kvFields = ();
   my @fields;
   my ($key, $val, $canset);

   while( <STDIN> ) {
	@fields = split " ";	# split input
	$key = $fields[0];
	$val = join(" ",@fields[1..$#fields]);
	next if(!defined($key) || ($key eq "") || ($key =~ /^#/));
        $key = uc $key;		# upper case
	$canset = $ValidKeys{$key};	
	if(defined($canset)) {
	    # process the field
	    if($canset == $SETTABLE) {
		$kvFields{$key} = $val;
		$count++;
	    } else {
	    	&print_dbgmsg("Unsettable field: $key $val");
	    }
	} else {
	    # not defined...unknown key
	    # Unknown field: $key $val;
	    &print_errmsg("EMSG106 $progname $key $val");
	}
   }
   
   if($count == 0) {
	#no fields will be updated
	return 0;
   }

   # merge the 'kvFields' as the blank-separated list
   # For example, KA=V1 KB=V2:
   my @mmInList = ();
   my @kvpair;
   my $kvStr;
   while( @kvpair = each %kvFields ) {
	if( $kvpair[0] =~ "LOGFILELEN" ) {
		$kvStr = "GSLogSize=$kvpair[1]";
		push @mmInList, ($kvStr);
	} elsif( $kvpair[0] =~ "LOGDIRSIZE" ) {
		$kvStr = "GSMaxDirSize=$kvpair[1]";
		push @mmInList, ($kvStr);
	}
   }

   my $mmInStr = join(" ",@mmInList);
   `/opt/rsct/bin/chrsrc -c IBM.RSCTParameters $mmInStr`;
   $rc = $?;
   &print_dbgmsg("Update: $mmInStr RC=$rc");
   
   return $count;
}