#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2018,2020,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r721 src/43haes/usr/sbin/cluster/utilities/harc.net.sh 1.4.11.2 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 1990,2016 
# 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 
# @(#)  7d4c34b 43haes/usr/sbin/cluster/utilities/harc.net.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM
###############################################################################
#
#   COMPONENT_NAME: UTILITIES
#
#   FUNCTIONS: init_host, start_nfs_daemons
#
###############################################################################
#
# harc.net -	Starts necessary network and inet daemons for use by 
#		HACMP for AIX configuration utilities.
#
# Arguments: None
#
# Usage: harc.net
#
###############################################################################

###############################################################################
# clutils_log
#
# Description:
#       Write a message to the log file
#
# Arguments: None
#
###############################################################################

clutils_log()
{
    typeset PS4_FUNC="clutils_log"
    echo "$(date) $PROGNAME: $*" >> $CLUTILS_LOG_FILE
}

###############################################################################
# init_host
#
# Description:
#       For initializing AIX after a mksysb restore has been done.
#
# Arguments: None
#
###############################################################################

init_host ()
{
    typeset PS4_FUNC="init_host"
    /usr/sbin/hostid $(hostname)
    [[ $(/bin/uname -n) == "localhost" || -z $(/bin/uname -n)  ]] && \
	$(/bin/uname -S $(hostname|sed 's/\..*$//'))
}

###############################################################################
# start_nfs_daemons
#
# Description:
#       Start the NFS daemons if they are configured, and if the
#       customer wants them enabled at startup.
#
# Note: The check for 2 node cluster has been removed. This was intended
#       to endure that NFSv2 and NFSv4 was not used on more than 2 nodes.
#       However, it is valid to have 2 resource groups, one on nodes A and B
#       and the other on nodes C and D, with each exporting NFSv2/3,
#       file systems, making the 2 node cluster check invalid.
# 
# Arguments: None
#
###############################################################################

start_nfs_daemons ()
{
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
    typeset PS4_FUNC="start_nfs_daemons"
    clutils_log "start_nfs_daemons"

    #  
    : If this is a two node cluster and exported filesystems exist, then start all
    : proper NFS daemons
    #

    FOUND_V2V3='false'          # only need to find this once
    FOUND_V4='false'            # only need to find this once

    RESOURCE_GROUPS=$(odmget HACMPgroup | grep 'group =' | awk '{print $3}' | sed 's/"//g')
    for group in $RESOURCE_GROUPS
    do
        if [[ $FOUND_V2V3 == "true" &&  $FOUND_V4 == "true" ]]
        then
            # 
            : we already found both types in a previous RG
            : therefore, no need to start any more daemons
            # 
            break
        fi

        EXPORTLIST_V2V3=$(odmget -q "group=$group AND name=EXPORT_FILESYSTEM" HACMPresource \
                | grep value | awk '{print $3}' | sed 's/"//g')
        EXPORTLIST_V4=$(odmget -q "group=$group AND name=EXPORT_FILESYSTEM_V4" HACMPresource \
                | grep value | awk '{print $3}' | sed 's/"//g')

        if [[ -n "$EXPORTLIST_V2V3" || -n "$EXPORTLIST_V4" ]]  && [[ $FOUND_V2V3 == 'false' ]] && [[ $FOUND_V4 == 'false' ]]
        then
            # 
            : we found an exportlist and had not found any in a previous RG
            : therefore, start shared daemons
            : enable grace periods and start nfsd
            # 
            clutils_log "Start NFS daemons"
            chnfs -I -g on -x 1
            startsrc -s nfsd
            startsrc -s rpc.mountd
        fi

        if [[ -n $EXPORTLIST_V4 && $FOUND_V4 == "false" ]]
        then
            # 
            : we found a V4 export here and had not found one before
            : therefore, start V4 specific daemon
            # 
            startsrc -s nfsrgyd
            FOUND_V4='true'
        fi

        if [[ -n $EXPORTLIST_V2V3 && $FOUND_V2V3 == "false" ]]
        then
            # 
            : we found a V2/V3 export here and had not found one before
            : therefore, start V2/V3 specific daemons
            # 
            startsrc -s rpc.statd
            startsrc -s rpc.lockd
            FOUND_V2V3='true'
        fi
    done
}


###############################################################################
#
#   Routine to ensure that a third party repository and back up repository
#   disk is registered with Storage Framework.  This precludes having CAA
#   do an exhaustive scan.
#
#   Code below assumes a non-sited cluster.  The extension to a sited 
#   cluster would require finding the sircol associated with the local node.
#
###############################################################################

function register_pvid
{
    PS4_FUNC='register_pvid'
    [[ $VERBOSE_LOGGING == 'high' ]] && set -x
    typeset reg_pvid=$1

    #
    :	The disk of interest is on pvid $reg_pvid 
    #
    reg_disk=$(clodmget -q "attribute = pvid and value like ${reg_pvid}*" -f name -n CuAt 2>/dev/null)

    if [[ -n $reg_disk ]]
    then
	#
	:   The repository is disk $reg_disk.  Check for registration
	#
	sfwinfo=$(LC_ALL=C clras sfwinfo -d $reg_disk 2>/dev/null)
	if [[ $sfwinfo == @(*not registered*) ]]
	then
	    #
	    :	Storage Framework says the disk is not registered.
	    :	So, try to register it so that CAA does not have to
	    :	look at them all
	    #
	    clras 3rdpartydisk -s $reg_disk
	    clras 3rdpartydisk -g $reg_disk
	    print 'y' | clras 3rdpartydisk -r $reg_disk
	fi
    fi
}


function register_repository
{
    PS4_FUNC='register_repository'
    [[ $VERBOSE_LOGGING == 'high' ]] && set -x
    #
    :   Find all repository disks, and register if not registered already
    #
    for rep_pvid in $(clodmget -f repository -n HACMPsircol 2>/dev/null)
    do
	#
	:   See if the repository disk with pvid $rep_pvid is registered 
	:   to Storage Framework.	If not, try to register it.
	#
	register_pvid $rep_pvid
    done

    #
    :   Now, do the backup repositories
    #
    for back_up_pvid in $(clodmget -f backup_repository -n HACMPsircol 2>/dev/null)
    do
	#
	:   See if the backup repository disk with pvid $back_up_pvid is registered 
	:   to Storage Framework.	If not, try to register it.
	#
	register_pvid $back_up_pvid
    done
    #
    :   Make sure CAA picks this up
    #
    state=$(LC_ALL=C lsdev -l cluster0 | cut -d' ' -f2)
    if [[ $state == "Defined" ]]
    then
        mkdev -l cluster0
    fi

}

################################################################################
#
#   Name: refresh_rsyslogd
#
#   Description: refresh_rsyslogd performs stop and start rsyslogd deamon
#   and log the errors if any.
#
#   Inputs:  None
#
#   Returns: 0 or 1
#
################################################################################
function refresh_rsyslogd {

    PS4_FUNC='refresh_rsyslogd'
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    integer MAX_TRIES=$(clodmget -n  -q "subsysname = 'syslogd'" -f waittime SRCsubsys)
    integer retry_count=0
    integer rc=0
    typeset SYSLOG_RESTART="stopsrc -s syslogd; sleep 1; startsrc -s syslogd"

    stopsrc -cs syslogd

    #verify if syslogd is really stopped or not
    if [[ -z $(LC_ALL=C lssrc -s syslogd | grep -w "inoperative") ]]
    then
        for (( retry_count=1 ; retry_count<=$MAX_TRIES ; retry_count++ ))
        do
          sleep 1
          if [[ -n $(LC_ALL=C lssrc -s syslogd | grep -w "inoperative") ]]
          then
              break
          fi
        done
    fi

    if [[ -n $(LC_ALL=C lssrc -s syslogd | grep -w "inoperative") ]]
    then
        startsrc -s syslogd
        if [[ -z $(LC_ALL=C lssrc -s syslogd | grep -w "active") ]]
        then
            for (( retry_count=1 ; retry_count<=$MAX_TRIES ; retry_count++ ))
            do
              sleep 1
              if [[ -n $(LC_ALL=C lssrc -s syslogd | grep -w "active") ]]
              then
                  break
              fi
            done
        fi

        if [[ -z $(LC_ALL=C lssrc -s syslogd | grep -w "active") ]]
        then
            rc=1
        fi
    else
        rc=1
    fi
    if (( $rc != 0 ))
    then
        # something is really bad, unable to refresh syslog daemon
        dspmsg scripts.cat 10747 "Not able to restart the syslogd daemon. Try restarting the syslogd daemon using the following commands\n\
${SYSLOG_RESTART}\n\
If the problem persists, contact IBM support.\n" "${SYSLOG_RESTART}" 1>&2
    fi

}

###############################################################################
#
# Main Starts Here
#
###############################################################################
[[ "$VERBOSE_LOGGING" == "high" ]] && set -x
[[ "$VERBOSE_LOGGING" == "high" ]] && version='1.4.11.2'
PROGNAME=$(basename ${0})
PATH="$(/usr/es/sbin/cluster/utilities/cl_get_path all)"
HA_DIR="$(cl_get_path)"

HWUNDO_PROG="/usr/${HA_DIR}/sbin/cluster/.hwundo"
NFSO_PROG="/usr/sbin/nfso"
SERVER_STATUS_FILE="/usr/${HA_DIR}/sbin/cluster/server.status"
FORCE_DOWN_STATUS_FILE="/usr/es/sbin/cluster/etc/ClSm"

# Setup the log file
ODMDIR="/etc/${HA_DIR}/objrepos"
DEFAULTLOGDIR="/var/hacmp/log"

STANZA=$(odmget -q"name = clutils.log" HACMPlogs)
if [[ $STANZA != "" ]]
then
    DESTDIR=$(echo $STANZA | cut -d'"' -f8)
    CLUTILS_LOG_FILE="$DESTDIR/clutils.log"
else
    CLUTILS_LOG_FILE="$DEFAULTLOGDIR/clutils.log"
fi

clutils_log " $*"

###############################################################################
# Cleanup ODM if we got caught in the middle
# of a hardware address swap.
###############################################################################
if [[ -x ${HWUNDO_PROG} ]]
then
    clutils_log "Cleanup ODM"
    ${HWUNDO_PROG}
fi

###############################################################################
# Alert operator of presense of any VG replay files that may exist
###############################################################################
VGreplay=$(ls /usr/${HA_DIR}/sbin/cluster/etc/vg/*.replay 2>/dev/null)
if [[ -n $VGreplay ]]
then
    clutils_log "Replay files found"
    print "replay files found:"
    for i in $VGreplay ; do
        clutils_log "    $i"
	print "    $i"
    done
fi

###############################################################################
# Get HACMP for AIX environment variables
###############################################################################
LOCALNODENAME=$(odmget HACMPcluster | grep -w nodename | cut -d'"' -f2)
eval $(cllsparam -n $LOCALNODENAME)

###############################################################################
# Determine telinit mode (disabled is default)
###############################################################################

USE_TELINIT_FILE="/usr/${HA_DIR}/sbin/cluster/.use_telinit"

if [[ -f $USE_TELINIT_FILE ]]
then
    clutils_log "telinit enabled"
    USE_TELINIT=1
else
    clutils_log "telinit disabled (default mode)"
    USE_TELINIT=0
fi

###############################################################################
# Init uname and remove or clear status files
###############################################################################

init_host

if (( USE_TELINIT )) && [[ $PPID != 1 ]]
then
    clutils_log "Invoke rc.net -boot"
    /etc/rc.net -boot
fi

rm -f ${SERVER_STATUS_FILE}
rm -f ${FORCE_DOWN_STATUS_FILE}

###############################################################################
# This clears /etc/xtab, since rc.nfs is not run at boot time
# Restore /etc/exports from save copy, if needed (see cl_telinit)
# Start nfsd and rpc.mountd, if needed
###############################################################################
clutils_log "Invoke cl_telinit -boot"
cl_telinit -boot

###############################################################################
# Update System Resource Controller (to recognize new inet addresses)
###############################################################################
clutils_log "Update SRC for new inet addresses"
clrefresh_src

###############################################################################
# See if syslogd already running.  If not, start it based on the syslog type
# stored in syslog subsystem odm
###############################################################################
if ! /bin/ps -e | /bin/grep -s syslog 2>&1 > /dev/null
then
    typeset syslog_type=$(clodmget -n -q "subsysname = 'syslogd'" -f path SRCsubsys)
    if [[ ${syslog_type} == "/usr/sbin/rsyslogd" ]]
    then
        clutils_log "start rsyslogd"
        startsrc -s syslogd
    else
        clutils_log "start syslogd"
        startsrc -s syslogd
    fi  
fi

###############################################################################
# Start portmapper and inet daemon.
###############################################################################
if (( USE_TELINIT ))
then
    clutils_log "start portmap and inetd"
    startsrc -s portmap
    startsrc -s inetd
fi

###############################################################################
# Configure persistent addresses
###############################################################################

if (( ! USE_TELINIT ))
then
    clutils_log "configure etherchannel"
    /usr/lib/methods/cfgech -2

    clutils_log "Configure interfaces"
    AIX_CFGMGR_MODE=1 /usr/lib/methods/cfgif >> $CLUTILS_LOG_FILE 2>&1

    clutils_log "configure all persistent IP addresses"
    cl_configure_persistent_address config_all -d -B
    clutils_log "install any default routes on persistent subnets added as static routes or through /etc/rc.net"
    /etc/route -n -f   >> $CLUTILS_LOG_FILE 2>&1
    /etc/rc.net -boot >> $CLUTILS_LOG_FILE 2>&1

    # Because of 'route -n -f' above, the default routes will be deleted and remote logging stops
    # Due to this, already running connection traffic (forwarding syslog messages to remote machine)
    #   going to different subnet will get effected.
    # Default route gets established by command 'rc.net -boot'
    # So, to resume remote logging, refresh syslogd/rsyslogd daemon now

    typeset syslog_type=$(clodmget -n -q "subsysname = 'syslogd'" -f path SRCsubsys)
    if [[ ${syslog_type} == "/usr/sbin/rsyslogd" ]]
    then
        clutils_log "Refreshing rsyslogd daemon from harc.net"
        # stop and start syslogd as rsyslogd does not support refresh mechanism
        refresh_rsyslogd >> $CLUTILS_LOG_FILE 2>&1
    else
        clutils_log "Refreshing syslogd daemon from harc.net"
        refresh -s syslogd >> $CLUTILS_LOG_FILE 2>&1
    fi
fi

###############################################################################
# Enable JFS log copy of dup cache entries
###############################################################################

if [[ -x ${NFSO_PROG} ]] 
then
    clutils_log "${NFSO_PROG} -H enable_ha"
    "${NFSO_PROG}" -H enable_ha
fi

##########################################################################
# The following commented line may be uncommented if you need to start
# the NFS daemons upon boot, but if you do so, some lock
# reclaim requests may be sent out by NFS before the node is on its
# service address which may result in long delays and result in possible
# client loss of locks they would have reclaimed.
##########################################################################
#           start_nfs_daemons

#
:   Turn on any iSCSI software support
#
LC_ALL=C lsdev -t iscsi | while read device status rest 
do

    if [[ $device == @(iscsi[0-9]*) && $status == "Available" ]]
    then
	#
	:   If this is an available iSCSI device, 
	:   configure it, and any autovaryon volume groups under it
	#
	cfgmgr -l $device
	cl_cfgvg $device
    fi
done

##########################################################################
#
:   If the repository disk is not currently registered to Storage Framework
:   register it now, to avoid CAA having to do a serial search.
#
##########################################################################
register_repository

clutils_log "exit 0"
exit 0
