#! /bin/ksh
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 1997,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 = "@(#)58   1.41   src/rsct/pgs/cmds/aix/hagsglsm.sh, gsctrl, rsct_rady, rady2035a 11/12/15 16:44:36"
#*======================================================================
#*
#* Module Name:  hagsglsm
#*
#* Description:
#*      Script to start the Group Services Daemon as an SRC subsystem.
#*
#*      This file is formatted with tabstops of 4.
#*======================================================================

#Fix for Defect 181688
unalias -a

#########################################################################
# Get the current Locale and determine whether English output is also needed
# Output: LOCALE
#	  PRINT_ENG_MSG
#########################################################################
get_current_locale()
{
   # Check if current locale is a English
   LOCALE=`/usr/bin/locale`
   # /usr/bin/locale may produce LC_MESSAGES=en_US or LC_MESSAGES="en_US".
   # We use two sed "s" commands, the first one gets rid of LC_MESSAGES=,
   # the second one removes the two surrounding '"' if they are there.
   LOCALE=`echo "$LOCALE" | grep LC_MESSAGES | sed "s/LC_MESSAGES=//;s/\"//g"`

   # Do not print English messages if the local language is English.
   # C and POSIX are special locales. Treat them as en_US.
   if [[ "$LOCALE" = "C" || "$LOCALE" = "POSIX" ]]; then
	PRINT_ENG_MSG="NO"
   else
	# A locale may look like en_US or en_US.ISO8859-1. Use cut command
	# to remove the language encoding.
	LOCALE=`echo "$LOCALE" | cut -f 1 -d "."`
	if [[ "$LOCALE" = "en_US" || "$LOCALE" = "En_US" || "$LOCALE" = "en_GB" || "$LOCALE" = "En_GB" ]]
	then
		# Local language is English.
		PRINT_ENG_MSG="NO"
	else
		# Local language is not English (including "$LOCALE"=""),
		# which should not happen in normal cases)
		PRINT_ENG_MSG="YES"
	fi
   fi
}

#########################################################################
#                                                                       #
# Function: print_message                                               #
# Description: wrapper for message printing. All messages go to stderr. #
#     For now, all messages are printed in both English and the current #
#     language unless current language is en_US, C, or POSIX.           #
#                                                                       #
#     This subroutine makes it easy to print messages in  either English#
#     or current language or both. Also, it ensure all messages will be #
#     printed to the same stream.                                       #
#########################################################################

print_message()
{
    MSGCMD="/opt/rsct/bin/hadspmsg hagsctrl ha_gs.cat"
    print -u2 "`${MSGCMD} $*`"

#    if [[ $PRINT_ENG_MSG = "YES" ]]
#    then
#        print -u2 "`LC_ALL=en_US ${MSGCMD} $*`"
#    fi
}

#########################################################################
#
# Function: refresh_subsys
# Description: build a AggregateIP configuration table 
#		at SW_GROUPIE_AGGIP_CFG.
#	The format of the AggregateIP.cfg are
#		# list of <node> <ml-device> <agg_list>
#		1 	ml0	css0,css1
#		2	ml0	css0
#		...
#	If it hits an error, exit with the non-zero.
#########################################################################
refresh_subsys()
{
   # set keywords which are understandable by hagsglsmd
   KW_SWPLANES="+SwitchPlanes"
   KW_INSTALLED="+Installed"
   KW_ECHO="+echo"
   KW_CFGID="+CFGID"

   if [[ -z $SW_GROUPIE_AGGIP_CFG ]]; then
	# No Aggregate IP cfg is not defined.
	print_message EMsg_AggIP_Cfg_Not_Defined hagsglsmd
	exit 2
   fi

   cfgid=0
   _date=$(date)
   echo "$_date - Refresh request by the daemon is accepted"

   #empty file
   rm -f $SW_GROUPIE_AGGIP_CFG

   # Ensure file created has correct permissions
   umask 022

   if [[ $HA_DOMAIN_TYPE != "PSSP" ]]; then
	# AggregateIP on ml0 is not supported.
  	print_message EMsg_AggIP_Not_Supported hagsglsmd $HA_DOMAIN_TYPE
	msg="Aggregate_IP group for /dev/ml0 not supported on $HA_DOMAIN_TYPE"
	echo "${KW_ECHO}: ${msg}" >> $SW_GROUPIE_AGGIP_CFG
	echo "${KW_CFGID}: ${cfgid}" >> $SW_GROUPIE_AGGIP_CFG
   	echo "# Date: $_date" >> $SW_GROUPIE_AGGIP_CFG
	exit 1
   fi

   #
   # Create AggregateIP.cfg using SDR
   #
   # find the switch type & number planes
   sw_name=`SDRGetObjects -x Switch -d : switch_name | grep SP_Switch2 | uniq`
   num_planes=`SDRGetObjects -x SP number_switch_planes`
   echo "${KW_SWPLANES}: ${num_planes}" >> $SW_GROUPIE_AGGIP_CFG
   echo "${KW_INSTALLED}: css0" >> $SW_GROUPIE_AGGIP_CFG
   if [[ $sw_name = SP_Switch2 && $num_planes -gt 1 ]]; then
	echo "${KW_INSTALLED}: css1" >> $SW_GROUPIE_AGGIP_CFG
   fi

   SDRGetObjects -x Aggregate_IP \
	node_number device_name agg_list >> $SW_GROUPIE_AGGIP_CFG
   _rc=$?
   if [[ $_rc -eq 26 ]]
   then
	msg="Aggregate_IP SDR class not found, or Aggregate_IP not configured"
	echo "${KW_ECHO}: ${msg}" >> $SW_GROUPIE_AGGIP_CFG
	echo "${KW_CFGID}: ${cfgid}" >> $SW_GROUPIE_AGGIP_CFG
   	echo "# Date: $_date" >> $SW_GROUPIE_AGGIP_CFG
	exit 0;
   fi
   
   if [[ $_rc -ne 0 ]]
   then
	# Error on reading Aggregate_IP from SDR
	print_message EMsg_Cannot_Get_Aggregate_IP_Cfg
	msg="Aggregate_IP can not be retrived from SDR (SDR_rc=$_rc)"
	echo "${KW_ECHO}: ${msg}" >> $SW_GROUPIE_AGGIP_CFG
	echo "${KW_CFGID}: ${cfgid}" >> $SW_GROUPIE_AGGIP_CFG
   	echo "# Date: $_date" >> $SW_GROUPIE_AGGIP_CFG
	exit 3
   fi

   # everything was perfect!!
   # compute checksum of the file
   cksum $SW_GROUPIE_AGGIP_CFG | read cfgid junk1
   echo "${KW_CFGID}: ${cfgid}" >> $SW_GROUPIE_AGGIP_CFG

   msg="Aggregate_IP is successfully obtained from SDR"
   echo "${KW_ECHO}: ${msg}" >> $SW_GROUPIE_AGGIP_CFG
   echo "# Date: $_date" >> $SW_GROUPIE_AGGIP_CFG
   exit 0
}


#########################################################################
# Main starts here
# We set stdout and stderr to the same file in mkssys
# However, the src opens them separately, so they overwrite each other.
# To fix it, we make stderr a copy of stdout here.
#
# 1. Normal startup by SRC:
#   	hagsglsm <domainType> -p <partition> -d <default_log_file>
#	i.e., hagsglsm PSSP -p c47s -d hagsglsm.default.log
#    Under HAES 4.2.2
#   	hagsglsm -p <domain_name> -d <default_log_file>
#    Script will set SW_GROUPIE_REFRESH_CMD to $0 before it starts daemon.
#    hagsglsmp will set SW_GROUPIE_AGGIP_CFG
#
# 2. Refresh request by hagsglsmd
#	hagsglsm -c refresh
#	Environment set by the requestor(daemon):
#		HA_DOMAIN_TYPE
#		SW_GROUPIE_AGGIP_CFG by the daemon or the hagsglsmp
#
#########################################################################

exec 2<&1   # make stderr a copy of stdout

#
# Get Program name
PROGNAME=`basename $0`

#
umask 022

# setup the locale
get_current_locale

# print the command line
echo "Command started: $0 $*"

# check the parameters whether the request is for refresh
if [[ $1 = "-c" && $2 = "refresh" ]]
then
   # process the refresh here

   refresh_subsys

   # exit here
   exit 0;
fi

#
# set SW_GROUPIE_REFRESH_CMD to myself so that the daemon will know me.
export SW_GROUPIE_REFRESH_CMD=$0
echo "SW_GROUPIE_REFRESH_CMD=$SW_GROUPIE_REFRESH_CMD"

#

domType=$1                      # The domain we are in
#
# Determine if being called with HACMP parameters.  These could be the
# back-level ones, if HA/ES 4.2.x is installed.  If so, then we need to
# handle them differently.
#
if [[ ${domType} = "-p" ]]
then
  #echo "Parameter line is HACMP/ES 4.2.x style.  Assuming HAES domain."
  print_message EMsg_Param_Is_For_HAES_42x hagsglsmd
  DomainParameter="yes"         # Domain name given in parameter line
  DomainName=$2
  shift                         # Shift both -p <domName>
else
  DomainParameter="no"
fi
shift                           # Get rid of first arg
ARGS=$*                         # Preserve remainder

# This script expects to be called in two disparate environments:
#  - PSSP realm
#  - HA/ES realm
#  - CLUSTER realm
# We need to expect various services, such as perl, to be in
# completely different places.

SUBTYPE=${SW_GROUPIE_SUBSYS:-$domType}
echo "DomainType=$domType"

case $SUBTYPE in
  hagsglsm|PSSP ) 	PGSDSUBSYS=hags; SUBSYS=hagsglsm; domain=PSSP
			;;
  grpglsm|HAES ) 	PGSDSUBSYS=grpsvcs; SUBSYS=grpglsm; domain=HAES
		 	export SW_GROUPIE_DAEMON=hagsglsmd
		 	;;
  ctgrpglsm|CLUSTER ) 	PGSDSUBSYS=ctgrpsvcs; SUBSYS=ctgrpglsm; domain=CLUSTER
		 	export SW_GROUPIE_DAEMON=hagsglsmd
			;;
  * ) SUBSYS=$SUBTYPE; domain=TEST;;
esac

export HA_DOMAIN_TYPE=$domain

# set the flag whether 'ioctl()' for switch has to be enabled or not
if [[ $SUBSYS != "hagsglsm" ]]; then
	# disable ioctl() for majority 
	export CSSPDD_NO_MAJOR_IOCTL=1
fi

# remove all limits: core, data, filesize, data, stack, cpu time
# both hard and soft
ulimit -c unlimited
ulimit -d unlimited
ulimit -f unlimited
ulimit -m unlimited
ulimit -s unlimited
ulimit -t unlimited


#
# Init FFDC
#

. /opt/rsct/bin/fcinit.sh -l

RC=$?
if [[ $RC -ge 3 ]]
then
   # Can not initialize FFDC environment. RC=$RC
   print_message EMsg_Cannot_Initialize_FFDC ${PROGNAME} $RC
else
   export SW_GROUPIE_FFDC_INIT_DONE=1
fi

FCLOGERR_X="ALPHA"
FCLOGERR_Y="100"


# Locating the node number differs, based on realm.  The node_number
# utility is part of the PSSP.  clnodenumber is part of HACMP.  Also,
# if HA, set path.

export RSCTPATH=/opt/rsct/bin:/opt/rsct/install/bin
export PATH=$PATH:/usr/sbin:/usr/bin:/bin
if [[ ${domain} = PSSP ]]
then
    export PGSD_SUBSYS=$PGSDSUBSYS
    export PATH=$RSCTPATH:/usr/lpp/ssp/bin:/usr/lpp/ssp/install/bin:$PATH
    perl=/usr/bin/perl
    export SW_GROUPIE_NODE_NUMBER=$(node_number)
    DomainFlag=""
    echo "Node number="$SW_GROUPIE_NODE_NUMBER"  Args="${ARGS}
elif [[ ${domain} = HAES ]]
then
    export PGSD_SUBSYS=$PGSDSUBSYS
    export SW_GROUPIE_SUBSYS=$SUBSYS
    export PATH=$RSCTPATH:/usr/es/sbin/cluster/utilities:$PATH
    if [[ -x /usr/bin/perl ]]
    then
        perl=/usr/bin/perl
    elif [[ -x /usr/es/sbin/cluster/utilities/perl ]]
    then
        perl=/usr/es/sbin/cluster/utilities/perl
    elif [[ -x /usr/sbin/cluster/utilities/perl ]]
    then
        perl=/usr/sbin/cluster/utilities/perl
    else
        perl=perl
    fi        
    if [[ -x /usr/es/sbin/cluster/utilities/cldomain ]]
    then
	DomainName=$(ODMDIR=/etc/es/objrepos /usr/es/sbin/cluster/utilities/cldomain)
    else
	export PATH=$PATH:/usr/sbin/cluster/utilities
	#echo "cldomain is not found, assuming HAES 4.2, use SP partition name."
	print_message EMsg_cldomain_Not_Found hagsglsmd
	export PATH=/usr/lpp/ssp/bin:/usr/lpp/ssp/install/bin:$PATH
	if [[ $DomainParameter = "yes" ]]
    	then
	    #echo "Using Domain Name given on parameter line: "$DomainName
            print_message EMsg_DomainName_On_Param_Used hagsglsmd $DomainName
	else
	    # get name of system partition we are in
      	    long_Syspar_name=$(spget_syspar -n)     
	    if [[ -z $long_Syspar_name ]]
	    then
		#print -u2 $tmsg
		#print_message EMsg_Unable_To_Get_Syspar_name hagsglsmd
                print_message EMsg_Cannot_Determine_Syspar_Name hagsglsmd
		tmsg="Cannot get system partition name with 'spget_syspar -n'."
		/opt/rsct/bin/fclogerr -x ${FCLOGERR_X} -y ${FCLOGERR_Y} \
		-d $tmsg -p $LINENO -s $0 -v "1.41" -l RSCT \
		-r "hagsglsm" -t ERRID_GS_GLSM_STARTERR_ER -e FFDC_ERROR \
		-i /opt/rsct/include/ha_gs.err.S.h \
		-b "hagsglsm: $tmsg"
		exit 1
	    fi
	    # Make host name short host name
	    DomainName=${long_Syspar_name%%.*} # strip off . and all that follows
	fi
	export PGSD_HAESLEVEL="42"
    fi
    DomainFlag="-p ${DomainName}"
    if [[ -z $HB_SERVER_SOCKET ]]
    then
        # No HB_SERVER_SOCKET is defined. Set it here
        HB_SERVER_SOCKET=/var/ha/soc/topsvcs/server_socket
    fi
    export HB_SERVER_SOCKET
    # Connect the HATS daemon
    NodeNum=`HB_SERVER_SOCKET=$HB_SERVER_SOCKET hats_node_number -d ${DomainName}`
    while ((0 != $?))
    do
        sleep 2
        NodeNum=`HB_SERVER_SOCKET=$HB_SERVER_SOCKET hats_node_number -d ${DomainName}`
    done

    export SW_GROUPIE_NODE_NUMBER=$NodeNum
    echo "Domain Name="$DomainName"  DomainFlag="$DomainFlag"  Node number="$NodeNum

elif [[ ${domain} = CLUSTER ]]
then
    export PGSD_SUBSYS=$PGSDSUBSYS
    export SW_GROUPIE_SUBSYS=$SUBSYS
    export PATH=/usr/sbin/ct/bin:$RSCTPATH:$PATH
    perl=/usr/bin/perl
    # Get the cluster ID & Name
    CLUSTER_ID=`ctgetclusterinfo -i`
    if [[ $? -ne 0 ]]; then
        tmsg="ctgetclusterinfo error = $!"
        print -u2 $tmsg

        /opt/rsct/bin/fclogerr -x ${FCLOGERR_X} -y ${FCLOGERR_Y} \
                -d $tmsg -p $LINENO -s $0 -v "1.41" -l RSCT \
                -r "hagsglsm" -t ERRID_GS_GLSM_STARTERR_ER -e FFDC_ERROR \
                -i /opt/rsct/include/ha_gs.err.S.h \
		-b "hagsglsm: $tmsg"
        exit 1
    fi

    # We are in CLUSTER
    CLUSTER_NAME=`ctgetclusterinfo -n`
    DomainName=${CLUSTER_NAME}

    # -p <cluster name> -i <cluster_id>
    DomainFlag="-p ${CLUSTER_NAME} -i ${CLUSTER_ID}"

    if [[ -z $HB_SERVER_SOCKET ]]
    then
        # No HB_SERVER_SOCKET is defined. Set it here
        HB_SERVER_SOCKET=/var/ct/${CLUSTER_ID}/soc/cttopsvcs/server_socket
    fi
    export HB_SERVER_SOCKET

    # Connect the HATS daemon
    NodeNum=`HB_SERVER_SOCKET=$HB_SERVER_SOCKET hats_node_number -d ${DomainName}`
    while ((0 != $?))
    do
        sleep 2
        NodeNum=`HB_SERVER_SOCKET=$HB_SERVER_SOCKET hats_node_number -d ${DomainName}`
    done

    export SW_GROUPIE_NODE_NUMBER=$NodeNum
    echo "Cluster DomainFlag="$DomainFlag" Node number="$NodeNum

else
    # Assume test, set for PSSP.
    export PATH=$RSCTPATH:/usr/lpp/ssp/bin:/usr/lpp/ssp/install/bin:$PATH
    perl=/usr/lpp/ssp/perl5/bin/perl
    export SW_GROUPIE_NODE_NUMBER=$(node_number)
    DomainFlag=""
    echo "Node number="$SW_GROUPIE_NODE_NUMBER"  Args="${ARGS}
fi

if [[ -n $SW_GROUPIE_PATH ]]
then
  export PATH=$SW_GROUPIE_PATH:$PATH
fi

echo "PATH=${PATH}"

export SW_GROUPIE_PERL=${perl}

# hagsreap will remove hags logs and core files so that they consume
# no more than sizeLimit bytes.
sizeLimit=${SW_GROUPIE_REAP_SIZE:-$((700 * 1024))} # default size is 700K
export SW_GROUPIE_REAP_SIZE=$sizeLimit
Command=${SW_GROUPIE_REAP_CMD:-Erase}
export SW_GROUPIE_REAP_CMD=$Command

# uncomment the following lines if 'csspdd_ioctl' should not be called
# export CSSPDD_NO_MAJOR_IOCTL=1

cmd="$perl /opt/rsct/bin/hagsglsmp -s ${SUBSYS} ${DomainFlag} ${ARGS}"

echo "$cmd"

exec $cmd

tmsg="exec $cmd failed! rc = $!, $(($!/256)) $(($!%256)) errno=$ERRNO "
tcmd="exec $cmd"
print_message EMsg_Command_Failed $tcmd $!
/opt/rsct/bin/fclogerr -x ${FCLOGERR_X} -y ${FCLOGERR_Y} \
        -d $tmsg -p $LINENO -s $0 -v "1.41" -l RSCT \
        -r $PROGNAME -t ERRID_GS_GLSM_STARTERR_ER -e FFDC_ERROR \
        -i /opt/rsct/include/ha_gs.err.S.h \
	-b "hagsglsm: $tmsg"
exit 1