#! /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 = "@(#)57   1.45   src/rsct/pgs/cmds/aix/hags.sh, gsctrl, rsct_rady, rady2035a 11/16/15 15:05:21"
#*======================================================================
#*
#* Module Name:  hags
#*
#* Description:
#*      Script to start the Group Services Daemon as an SRC subsystem.
#*
#*      This file is formatted with tabstops of 4.
#* Arguments: 
#*	Current : DomainType
#*   or HAES 4.2: -p DomainType
#* Note:
#*      DomainType should be one of "PSSP", "HAES", or "CLUSTER"
#*======================================================================

#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
}



# Main starts here
# However, the src opens them separately, so they overwrite each other.
# To fix it, we make stderr a copy of stdout here.

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

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

# restrict the default access
umask 022

# setup the locale
get_current_locale

#
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 hagsd
  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=${PGSD_SUBSYS:-$domType}

echo "Subtype="${SUBTYPE}

case $SUBTYPE in
  hags|PSSP ) 		SUBSYS=hags
			domain=PSSP
			;;
  grpsvcs|HAES ) 	SUBSYS=grpsvcs
			domain=HAES
			export PGSD_DAEMON=/opt/rsct/bin/hagsd
			;;
  ctgrpsvcs|CLUSTER )	SUBSYS=ctgrpsvcs
			domain=CLUSTER
			export PGSD_DAEMON=/opt/rsct/bin/hagsd
			;;
  * ) SUBSYS=$SUBTYPE; domain=TEST;;
esac


export HA_DOMAIN_TYPE=$domain

# We set stdout and stderr to the same file in mkssys
# 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

#
# Initialize FFDC for AIX LOG
. /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 PGSD_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

OSname=$(/bin/uname -s)

case "$OSname" in
  "AIX")
    export PATH=$PATH:/usr/sbin:/usr/bin
    ;;
  "Linux")
    export PATH=$PATH:/usr/sbin:/usr/bin:/bin
    ;;
  *)
    print_message EMsg_Internal_error hags
    exit 1
    ;;
esac

if [[ ${domain} = PSSP ]]
then
    export PATH=$RSCTPATH:/usr/lpp/ssp/bin:/usr/lpp/ssp/install/bin:$PATH
    perl=/usr/bin/perl
    export PGSD_NODE_NUMBER=$(node_number)
    DomainFlag=""
    echo "Node number="$PGSD_NODE_NUMBER"  Args="${ARGS}
elif [[ ${domain} = HAES ]]
then
    export PGSD_SUBSYS=$SUBSYS
    export PATH=$RSCTPATH:/usr/es/sbin/cluster/utilities:$PATH

    #which perl should be used?
    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

    # find domain name
    if [[ -x /usr/es/sbin/cluster/utilities/cldomain ]]
    then
	DomainName=$(ODMDIR=/etc/es/objrepos /usr/es/sbin/cluster/utilities/cldomain)
    else
	export PATH=$RSCTPATH:$PATH:/usr/sbin/cluster/utilities
	#echo "cldomain is not found, assuming HAES 4.2, use SP partition name."
	#echo "unset PGSD_TSCONFIG for the compatability"
	#unset PGSD_TSCONFIG
	print_message EMsg_cldomain_Not_Found hagsd
	if [[ $DomainParameter = "yes" ]]
	then
	    #echo "Using Domain Name given on parameter line: "$DomainName
	    print_message EMsg_DomainName_On_Param_Used hagsd $DomainName
	else
	    export PATH=/usr/lpp/ssp/bin:/usr/lpp/ssp/install/bin:$PATH
	    # 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 hagsd
		print_message EMsg_Cannot_Determine_Syspar_Name hagsd
		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.45" -l RSCT \
		-r $SUBSYS -t ERRID_GS_STARTERR_ER -e FFDC_ERROR \
        	-i /opt/rsct/include/ha_gs.err.S.h \
		-b "hags: $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

    # We are in HAES
    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

    # Now, I got the node number
    export PGSD_NODE_NUMBER=${NodeNum}
    echo "Domain Name="$DomainName" DomainFlag="$DomainFlag" Node number="$NodeNum

    # Allow memory room for TAMOS coexistence.
    # It's no longer needed, since hagsd is now compiled with less than 
    # 0x60000000.  
    # export LDR_CNTRL=MAXDATA=0x60000000

elif [[ ${domain} = CLUSTER ]]
then
    # CLUSTER here
    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.45" -l RSCT \
		-r $SUBSYS -t ERRID_GS_STARTERR_ER -e FFDC_ERROR \
		-i /opt/rsct/include/ha_gs.err.S.h \
		-b  "hags: $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

    # Now, I got the node number
    export PGSD_NODE_NUMBER=${NodeNum}
    echo "Cluster DomainFlag="$DomainFlag" Node number="$NodeNum
else
    # something else. Assume Test. Set for PSSP.
    export PATH=$RSCTPATH:/usr/lpp/ssp/bin:/usr/lpp/ssp/install/bin:$PATH
    perl=/usr/bin/perl
    export PGSD_NODE_NUMBER=$(node_number)
    DomainFlag=""
    echo "Node number="$PGSD_NODE_NUMBER"  Args="${ARGS}
fi

#
#
if [[ -n $PGSD_PATH ]]; then
  export PATH=$PGSD_PATH:$PATH
fi

export PATH=$PATH:/usr/sbin	# to include 'no' command
echo "PATH=${PATH}"
export PGSD_PERL=${perl}

# hagsreap will remove hags logs and core files so that they consume
# no more than sizeLimit bytes.
# NOTE: This will determined in "hagsp"
# sizeLimit=${PGSD_REAP_SIZE:-$((5 * 1024 * 1024))} # default size is 5M
# export PGSD_REAP_SIZE=$sizeLimit

Command=${PGSD_REAP_CMD:-Erase}
export PGSD_REAP_CMD=$Command

#-----------------------------------------------------
# PGSD_MAX_NODES_PER_BROADCAST: max # of nodes per broadcast
if [[ -z $PGSD_MAX_NODES_PER_BROADCAST ]]; then
        PGSD_MAX_NODES_PER_BROADCAST=64      # default 64 nodes
fi
export PGSD_MAX_NODES_PER_BROADCAST
echo "PGSD_MAX_NODES_PER_BROADCAST=${PGSD_MAX_NODES_PER_BROADCAST}"

# PGSD_REBROADCAST_NEXT_INTERVAL_MSECS: interval between broadcast
# The remainder nodes will be rebroadcast (in every 1.5 sec[1500msecs])
if [[ -z $PGSD_REBROADCAST_NEXT_INTERVAL_MSECS ]]; then
	PGSD_REBROADCAST_NEXT_INTERVAL_MSECS=1500   # 1.5 secs
fi
export PGSD_REBROADCAST_NEXT_INTERVAL_MSECS
echo "PGSD_REBROADCAST_NEXT_INTERVAL_MSECS=${PGSD_REBROADCAST_NEXT_INTERVAL_MSECS}"

#
#-----------------------------------------------------
# No more PRM delay because of the above chunking broadcast
#
# export PRM_DELAY_USEC_PER_KB_SEND=100 # (usecs/KB)
#-----------------------------------------------------

#-----------------------------------------------------
# Get the somaxconn to set backlog for listen() call
if [[ -z $PGSD_SOCKET_MAXCONN ]]; then
   case "$OSname" in
     "AIX")
        export PGSD_SOCKET_MAXCONN=$(no -o somaxconn | awk '{print $3}')
       ;;
     "Linux")
        if [ -r /proc/sys/net/core/somaxconn ]
        then
          export PGSD_SOCKET_MAXCONN=$(cat /proc/sys/net/core/somaxconn)
        fi
       ;;
     *)
       ;;
   esac
fi
echo "PGSD_SOCKET_MAXCONN=${PGSD_SOCKET_MAXCONN}"
#-----------------------------------------------------

exec $perl /opt/rsct/bin/hagsp -s ${SUBSYS} ${DomainFlag} ${ARGS}

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.45" -l RSCT \
	-r $SUBSYS -t ERRID_GS_STARTERR_ER -e FFDC_ERROR \
	-i /opt/rsct/include/ha_gs.err.S.h \
	-b "hags: $tmsg"
exit 1