#
# Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

SCLOGGER=/usr/cluster/lib/sc/scds_syslog
PKG=SUNWscmqi.siu
METHOD=`basename $0`
STOP_TIMEOUT=`/usr/cluster/bin/scha_resource_get -O Stop_timeout -R $RESOURCE -G $RESOURCEGROUP`
status=`/usr/cluster/bin/scha_resource_get -O STATUS -R $RESOURCE -G $RESOURCEGROUP`
STATUS=`echo $status | awk '{print $1}'`
LOGFILE=/var/tmp/${RESOURCE}_logfile
TASK_COMMAND=""
RESOURCE_PROJECT_NAME=""
SCHA_RESOURCEGROUP_GET=/usr/cluster/bin/scha_resourcegroup_get
SCHA_RESOURCE_GET=/usr/cluster/bin/scha_resource_get
SCHA_CLUSTER_GET=/usr/cluster/bin/scha_cluster_get

syslog_tag()
{
        #
        # Data Service message format
        #

        $SET_DEBUG

        print "SC[${PKG:-??}.${METHOD:-??}]:${RESOURCEGROUP:-??}:${RESOURCE:-??}"
}

scds_syslog()
{

        #
        # Log a message
        #

        $SET_DEBUG

        $SCLOGGER "$@" &
}

debug_message()
{
        #
        # Output a debug message to syslog if required
        #

        if [ "$DEBUG" = "$RESOURCE" -o "$DEBUG" = "ALL" ]
        then
                SET_DEBUG="set -x"

                DEBUG_TEXT=$1

                scds_syslog -p daemon.debug -t $(syslog_tag) -m \
                        "%s" "$DEBUG_TEXT"
        else
                SET_DEBUG=
        fi
}

log_message()
{
        #
        # Output a message to syslog as required
        #

        debug_message "Function: log_message - Begin"
        $SET_DEBUG

        if [ -s "${LOGFILE}" ]
        then
                PRIORITY=$1
                HEADER=$2

                if [ "${PRIORITY}" = "error" ]
                then
                        echo "The following command was executed - pgrep -fl -u $MQSIUSER" >> $LOGFILE
                        pgrep -fl -u $MQSIUSER >> $LOGFILE
                fi

                #
                # Ensure the while loop only reads a closed file
                #

                strings ${LOGFILE} > ${LOGFILE}.copy

                while read MSG_TXT
                do
                        scds_syslog -p daemon.${PRIORITY} -t $(syslog_tag) -m \
                                "%s - %s" \
                                "${HEADER}" "${MSG_TXT}"
                done < ${LOGFILE}.copy

		su ${MQSIUSER} -c "cat /dev/null > $LOGFILE" > /dev/null
		cat /dev/null > ${LOGFILE}.copy
        fi

        debug_message "Function: log_message - End"
}

validate_options()
{
        #
        # Ensure all options are set
        #

        for i in RESOURCE RESOURCEGROUP QMGR MQSIUSER
        do
                case $i in
                        RESOURCE)
                        if [ -z $RESOURCE ]; then
                                logger -p daemon.err \
                                "ERROR: `basename $0` Option -R not set"
                                exit 1
                        fi;;

                        RESOURCEGROUP)
                        if [ -z $RESOURCEGROUP ]; then
                                logger -p daemon.err \
                                "ERROR: `basename $0` Option -G not set"
                                exit 1
                        fi;;

                        QMGR)
                        if [ -z $QMGR ]; then
                                logger -p daemon.err \
                                "ERROR: `basename $0` Option -Q not set"
                                exit 1
                        fi;;

                        MQSIUSER)
                        if [ -z $MQSIUSER ]; then
                                logger -p daemon.err \
                                "ERROR: `basename $0` Option -U not set"
                                exit 1
                        fi;;
                esac
        done
}

validate()
{
        debug_message "Function: validate - Begin"
        $SET_DEBUG

        rc_validate=0

        #
        # Validate Group mqbrkrs and user IDs ${MQSIUSER} and root exists within group mqbrkrs
        #

        if cat /etc/group | awk -F: '{print $1}' | grep mqbrkrs > /dev/null
        then
                debug_message "Validate - Group mqbrkrs exists"

                if cat /etc/group | awk -F: '{ if ($1 == "mqbrkrs") print $4}' | grep root > /dev/null
                then
                        debug_message "Validate - Group mqbrkrs exists with user ID root"
                else
                        rc_validate=1

                        scds_syslog -p daemon.error -t $(syslog_tag) -m \
                        "Validate - User ID root is not a member of group mqbrkrs"
                fi
        else
                rc_validate=1

                scds_syslog -p daemon.error -t $(syslog_tag) -m \
                "Validate - Group mqbrkrs does not exist"
        fi

        #
        # Validate User ID ${MQSIUSER}
        #

        pgroup=`grep -w $MQSIUSER /etc/passwd | awk -F: '{print $4}'`

        if [ ! -z $pgroup ]
        then
                if cat /etc/group | awk -F: '{ if ($1 == "mqm") print $3}' | grep $pgroup > /dev/null
                then
                        debug_message "Validate - Primary group for userid $MQSIUSER is mqm"
                else
                        if cat /etc/group | awk -F: '{ if ($1 == "mqm") print $4}' | grep $MQSIUSER > /dev/null
                        then
                                debug_message "Validate - Secondary group for userid $MQSIUSER is mqm"
                        else
                                rc_validate=1

                                scds_syslog -p daemon.error -t $(syslog_tag) -m \
                                "Validate - Userid $MQSIUSER is not a member of group mqm"
                        fi
                fi

                if cat /etc/group | awk -F: '{ if ($1 == "mqbrkrs") print $3}' | grep $pgroup > /dev/null
                then
                        debug_message "Validate - Primary group for userid $MQSIUSER is mqbrkrs"
                else
                        if cat /etc/group | awk -F: '{ if ($1 == "mqbrkrs") print $4}' | grep $MQSIUSER > /dev/null
                        then
                                debug_message "Validate - Secondary group for userid $MQSIUSER is mqbrkrs"
                        else
                                rc_validate=1

                                scds_syslog -p daemon.error -t $(syslog_tag) -m \
                                "Validate - Userid $MQSIUSER is not a member of group mqm"
                        fi
                fi
        else
                rc_validate=1

                scds_syslog -p daemon.error -t $(syslog_tag) -m \
                "Validate - Userid $MQSIUSER is not a valid userid"
        fi

        #
        # Validate that /opt/mqsi and /var/mqsi exist
        #

        if [ -d /opt/mqsi -a -d /var/mqsi ]
        then
                debug_message "Validate - WebSphere MQ Broker file systems ok"
        else
                rc_validate=1

                scds_syslog -p daemon.error -t $(syslog_tag) -m \
                "Validate - WebSphere MQ Broker file systems not defined"
        fi

        #
        # Validate that /var/mqsi/locks is a symbolic link
        #

        if [ -h /var/mqsi/locks ]
        then
		debug_message "Validate - WebSphere MQ Broker /var/mqsi/locks is a symbolic link"
        else
                rc_validate=1

                scds_syslog -p daemon.error -t $(syslog_tag) -m \
                "Validate - WebSphere MQ Broker /var/mqsi/locks is not a symbolic link"
        fi

        debug_message "Function: validate - End"
}

standard_resource_get()
{
        debug_message "Function: standard_resource_get - Begin"
        $SET_DEBUG

        PROPERTY=$1

        ${SCHA_RESOURCE_GET} -R ${RESOURCE} -G ${RESOURCEGROUP} -O ${PROPERTY}

        s1=$?

        if [ "${s1}" -ne 0 ]; then
                debug_message "standard_resource_get - Get property ${PROPERTY} rc<${s1}>, ignore if SC3.0"
        fi

        debug_message "Function: standard_resource_get - End"
        return ${s1}
}

standard_resourcegroup_get()
{
        debug_message "Function: standard_resourcegroup_get - Begin"
        $SET_DEBUG

        PROPERTY=$1

        ${SCHA_RESOURCEGROUP_GET} -R ${RESOURCE} -G ${RESOURCEGROUP} -O ${PROPERTY}

        s1=$?

        if [ "${s1}" -ne 0 ]; then
                debug_message "standard_resource_get - Get property ${PROPERTY} rc<${s1}>, ignore if SC3.0"
        fi

        debug_message "Function: standard_resourcegroup_get - End"

        return ${s1}
}

srm_function()
{
        debug_message "Function: srm_function - Begin"
        $SET_DEBUG

        USER=$1
  
        #
        # If Solaris 8 just return
        #

        if [ `/usr/bin/uname -r` = "5.8" ];
        then
                return 0
        fi

        #
        # Retrieve RESOURCE_PROJECT_NAME
        #

        RESOURCE_PROJECT_NAME=`standard_resource_get RESOURCE_PROJECT_NAME`

        #
        # Retrieve RG_PROJECT_NAME if RESOURCE_PROJECT_NAME is not set
        #

        if [ -z "${RESOURCE_PROJECT_NAME}" ]; then

                RESOURCE_PROJECT_NAME=`standard_resourcegroup_get RG_PROJECT_NAME`
        fi

        #
        # Return if no projects are defined
        #

        if [ -z "${RESOURCE_PROJECT_NAME}" ]; then
                return 0
        fi

        #
        # Validate that $USER belongs to the project defined by
        # ${RESOURCE_PROJECT_NAME}
        #

        PROJ_MEMBER=`/usr/bin/projects ${USER} | /usr/bin/grep -w ${RESOURCE_PROJECT_NAME}`

        if [ -z "${PROJ_MEMBER}" ];
        then
             scds_syslog -p daemon.error -t $(syslog_tag) -m \
                        "Validate - The user %s does not belongs to project %s" \
                        "${USER}" "${RESOURCE_PROJECT_NAME}"
                return 1
        else
                debug_message "srm_function - User ${USER} belongs to project ${RESOURCE_PROJECT_NAME}"
        fi

        #
        # Set TASK_COMMAND
        #

        TASK_COMMAND="/usr/bin/newtask -p ${RESOURCE_PROJECT_NAME}"

        debug_message "Function: srm_function - End"

        return 0
}

create_dummy_process()
{
        debug_message "Function: create_dummy_process - Begin"
        $SET_DEBUG

        DUMMY_PROCESS="/tmp/${RESOURCE}_${RESOURCEGROUP}_dummy.csh"

	cat > ${DUMMY_PROCESS} <<-EOF
	#!/bin/csh

	while (1)
		sleep 3600
	end
	EOF

        /bin/chmod 755 ${DUMMY_PROCESS}

        ${DUMMY_PROCESS} &

        scds_syslog -p daemon.notice -t $(syslog_tag) -m \
                "Create_dummy_process - WebSphere MQ UserNameServer was manually started" 

        debug_message "Function: create_dummy_process - End"
}


check_qmgr_pids()
{
	# 
	# Check that the main Queue Manager pids are running
	#

        debug_message "Function: check_qmgr_pids - Begin"
	$SET_DEBUG

	rc_check_qmgr_pids=
	flag=	

	while [ "$rc_check_qmgr_pids" != 000 ]
	do
		rc_check_qmgr_pids=
		sleep 1

		for pid in amqzxma0 amqhasmx amqzllp0 
		do
			if ps -ef | grep $pid | grep $QMGR | \
				grep -v grep > /dev/null
			then
				rc=0
			else
				if [ "$flag" ]
				then
					rc=1
				else
					flag=set
						
					scds_syslog -p daemon.notice -t $(syslog_tag) -m \
					"Waiting for WebSphere MQ UserNameServer Queue Manager"
			
					rc=1
				fi
			fi
			rc_check_qmgr_pids=$rc_check_qmgr_pids$rc
		done
	done

        debug_message "Function: check_qmgr_pids - End"
}

start_uns()
{
        #
        # Start the MQSI UserNameServer
	#
        # mqsistart will start the Queue Manager if it is
        # not running. Unfortunately, we can't have that
        # behaviour, as the Queue Manager needs to be
        # managed by Sun Cluster and it's respective
        # PMF tag.
        #
        # So, we delay issuing a mqsistart until we can
        # at least see the main queue manager processes.
        # This loop continues until either the Queue
        # Manager becomes available or Start_timeout
        # expires for this resource.

        debug_message "Function: start_uns - Begin"
	$SET_DEBUG

	# Ensure that $LOGFILE is created by ${MQSIUSER}
	srm_function ${MQSIUSER} 
	su - ${MQSIUSER} -c "$TASK_COMMAND touch $LOGFILE"

	check_qmgr_pids

	rc_ping_qmgr=

	while [ "${rc_ping_qmgr}" != 0 ]
	do
		echo "ping qmgr" | runmqsc $QMGR > /dev/null
		rc_ping_qmgr=$?

		if [ "${rc_ping_qmgr}" = 0 ]
		then
			scds_syslog -p daemon.notice -t $(syslog_tag) -m \
			"WebSphere MQ UserNameServer Queue Manager available"

			# Test the MQSI Semaphores

			for semaphore in BrokerResourceTableLockSempahore RetainedPubsTableLockSemaphore
			do
				if [ -r /var/mqsi/locks/MQSeriesIntegrator2${semaphore} ]
				then
					semid_with_zeros=`cat /var/mqsi/locks/MQSeriesIntegrator2${semaphore}`
					semid=`expr $semid_with_zeros / 1`

					if ipcs -s | grep $semid > /dev/null
					then
						continue
					else
						scds_syslog -p daemon.notice -t $(syslog_tag) -m \
						"MQSeriesIntegrator2%s exists without an IPC semaphore entry" \
						"${semaphore}"

						scds_syslog -p daemon.notice -t $(syslog_tag) -m \
						"MQSeriesIntegrator2%s file deleted" \
						"${semaphore}"

						/usr/bin/rm /var/mqsi/locks/MQSeriesIntegrator2${semaphore}
					fi
				fi
			done
		
			if getent passwd ${MQSIUSER} | awk -F: '{print $7}' | grep csh > /dev/null
			then
				su - ${MQSIUSER} -c "$TASK_COMMAND env SC3_COMMAND=${START_COMMAND} mqsistart UserNameServer >& $LOGFILE" > /dev/null
				rc_mqsistart=$?
			else
				su - ${MQSIUSER} -c "$TASK_COMMAND env SC3_COMMAND=${START_COMMAND} mqsistart UserNameServer > $LOGFILE 2>&1" > /dev/null
				rc_mqsistart=$?
			fi

			break
		else
			scds_syslog -p daemon.error -t $(syslog_tag) -m \
				"start_uns - Waiting for WebSphere MQ UserNameServer Queue Manager" 
			sleep 2
		fi
	done

        debug_message "Function: start_uns - End"
}

orderly_stop_uns()
{
	# 
	# Orderly stop of services
	#

        debug_message "Function: orderly_stop_uns - Begin"
	$SET_DEBUG

        for func in stop_uns_immediate \
                    cleanup_uns
        do
		case $func in
			stop_uns_immediate)	((FORCE_TIME=$STOP_TIMEOUT *30/100));;
			cleanup_uns)		((FORCE_TIME=$STOP_TIMEOUT *5/100));;
                esac

		LOOP_TIME=$FORCE_TIME

                $func

                while (( $LOOP_TIME > 0 ))
                do
			# Match only UserNameServer and effective id and exclude all mqsi<commands>

			if pgrep -fl UserNameServer -u ${MQSIUSER} | grep -v mqsi > /dev/null
                        then
                                sleep 1
                                LOOP_TIME=`expr $LOOP_TIME - 1`
                        else
                                break
                        fi
                done

                # Test if we broke out of the loop
		# Match only UserNameserver and effective id and exclude all mqsi<commands>

		if pgrep -fl UserNameServer -u ${MQSIUSER} | grep -v mqsi > /dev/null 
                then
			# As we process stop_uns_immediate output
			# any messages that have been collected

			log_message notice mqsistop
			continue
		else
                        # Break out of running all the functions
			log_message notice mqsistop
                        break
                fi
	done

        debug_message "Function: orderly_stop_uns - End"
}

stop_uns_immediate()
{
	#
	# Immediately stop the MQSI UserNameServer
	#

        debug_message "Function: stop_uns_immediate - Begin"
	$SET_DEBUG

	srm_function ${MQSIUSER}

	if getent passwd ${MQSIUSER} | awk -F: '{print $7}' | grep csh > /dev/null
	then
		su - ${MQSIUSER} -c "$TASK_COMMAND env SC3_COMMAND=${STOP_COMMAND} mqsistop -i UserNameServer >& $LOGFILE &" > /dev/null
	else
		su - ${MQSIUSER} -c "$TASK_COMMAND env SC3_COMMAND=${STOP_COMMAND} mqsistop -i UserNameServer > $LOGFILE 2>&1 &" > /dev/null
	fi
	
        debug_message "Function: stop_uns_immediate - End"
}

cleanup_uns()
{
        #
        # Cleanup the MQSI UserNameServer
        #

        debug_message "Function: cleanup_uns - Begin"
	$SET_DEBUG

        if pgrep -fl -u ${MQSIUSER} ${BROKER} | grep -v mqsi > /dev/null
        then
                for pid in bipservice bipuns
                do
                        for i in `ps -ef | grep $pid | grep $BROKER | \
                                grep -v grep | awk '{print $2}'`
                        do
                                kill -9 $i
                        done
                done

		scds_syslog -p daemon.notice -t $(syslog_tag) -m \
		"All WebSphere MQ UserNameServer processes stopped"
        fi

        debug_message "Function: cleanup_uns - End"
}

set_status()
{
        #
        # Set appropriate resource status
        #

        debug_message "Function: set_status - Begin"
	$SET_DEBUG

        STATUS_TYPE=$1

        scha_resource_setstatus -R $RESOURCE -G $RESOURCEGROUP -s $STATUS_TYPE 

        rc_scha_resource_setstatus=$?

        if [ "$rc_scha_resource_setstatus" != 0 ]
        then
		scds_syslog -p daemon.error -t $(syslog_tag) -m \
                "set_status - rc<%s> type<%s>" \
                "${rc_scha_resource_setstatus}" "${STATUS_TYPE}"
        fi

        debug_message "Function: set_status - End"
}
