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

SCLOGGER=/usr/cluster/lib/sc/scds_syslog
PKG=SUNWscsps
METHOD=`basename $0`
LOGFILE=/var/tmp/${RESOURCE}_logfile
SCHA_RESOURCE_GET=/usr/cluster/bin/scha_resource_get
SCHA_RESOURCEGROUP_GET=/usr/cluster/bin/scha_resourcegroup_get
TASK_COMMAND=""
RESOURCE_PROJECT_NAME=""

get_fmri_parameters ()
{

# extract the smf properties, you need to call your agent commands

        debug_message "Function: get_fmri_parameters - Begin "
        ${SET_DEBUG}

# Resource name

	RESOURCE=`/usr/bin/svcprop -p parameters/Resource ${SMF_FMRI}`

# Resource Group

	RESOURCEGROUP=`/usr/bin/svcprop -p parameters/Resource_group ${SMF_FMRI}`

# Start Project

	Project=:default
	if /usr/bin/svcprop ${SMF_FMRI}|grep start/project >/dev/null
	then
		Project=`/usr/bin/svcprop -p start/project ${SMF_FMRI}`
		if [ "${Project}" != ":default" ]
		then
			PROJ_OPT=" -P ${Project}"
			ZONE_PROJECT=${Project}
		fi
	fi

# Parameter file

	PARFILE=`/usr/bin/svcprop -p parameters/Parameter_File ${SMF_FMRI}`

        debug_message "Function: get_fmri_parameters - End "
}

Remove_shared_memory()
{

	# removes the shared memory segments with no detached processesi of a user 

	$SET_DEBUG
        debug_message "Function: Remove_shared_memory - Start called with the following arguments "$*

	User=$1
	ipcs -ma |grep -w $User|awk '{print $2," ",$11," ",$12}' |&
	while read -p id cpid lpid
	do
		del=0
		ps -u $User -o pid|grep -w "$cpid">/dev/null
		if [ $? -ne 0 ];then
			ps -u $User -o pid|grep -w "$lpid">/dev/null
			if [ $? -ne 0 ];then
				del=1
			fi
		fi
		if [ $del -ne 0 ];then
			ipcrm -m $id
		fi
		
	done

        debug_message "Function: Remove_shared_memory - End"
}

Check_InterRG_dependency()
{
        if [ -z "`/usr/cluster/bin/scrgadm -pvv -j ${RESOURCE} | /bin/grep Resource_dependencies_restart`" ]; then

                scds_syslog -p daemon.error -t $(syslog_tag) -m \
               "No Inter RG-dependency found, using internal dependency"

                USE_INTERNAL_DEP=TRUE
        fi
}

validate_options()
{
        #
        # Ensure all options are set
        #
	
	rc_validate_options=0

	SCRIPTNAME=`basename $0`
        for i in RESOURCE RESOURCEGROUP PARFILE USE_INTERNAL_DEP
        do
                case $i in
                        RESOURCE)
                        if [ -z "$RESOURCE" ]; then
                                scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate_options: HA N1 Grid Service Provisioning System %s Option %s is not set" \
                                "${SCRIPTNAME}" "-R" 
				rc_validate_options=1
                        fi;;

                        RESOURCEGROUP)
                        if [ -z "$RESOURCEGROUP" ]; then
                                scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate_options: HA N1 Grid Service Provisioning System %s Option %s is not set" \
                                "${SCRIPTNAME}" "-G" 
				rc_validate_options=1
                        fi;;

			PARFILE)
			if [ -z "$PARFILE" ]; then
				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate_options: HA N1 Grid Service Provisioning System %s Option %s is not set" \
                                "${SCRIPTNAME}" "-N" 
				rc_validate_options=1
			fi;;

                        USE_INTERNAL_DEP)
                        if [ "${USE_INTERNAL_DEP}" = "FALSE" ]; then
				Check_InterRG_dependency
                        fi;;

                esac
        done

	return ${rc_validate_options}
}

validate()
{
	#
	# Validate N1 Grid Service Provisioning System
	#
	
        debug_message "Function: validate - Begin"
	$SET_DEBUG

	rc_validate=0

	#
	# Validate that ${filename} exists
	#

	if [ ! -f "${PARFILE}" ]
	then
   		scds_syslog -p daemon.err -t $(syslog_tag) -m \
			"Validate - file %s does not exist" \
			"${PARFILE}"
		rc_validate=1
		return $rc_validate
	else
		debug_message "Validate - ${PARFILE} exists"
	fi

	debug_message "Validate - check the semantic if ${PARFILE} exists"

	# check if the parameter file is syntax and semantic is correct

	ksh -n ${PARFILE} >/dev/null 2>&1
	if [ $? -ne 0 ]; then
   			scds_syslog -p daemon.err -t $(syslog_tag) -m \
                "validate: there are syntactical errors in the parameterfile %s " \
		"${PARFILE}"
		rc_validate=1
		return $rc_validate
        fi
		
	# Test if all the mandatory variables are included and set correctly in the parameterfile 

	PARLIST="User Basepath Host Tport Startwait TestCmd ReturnString"
	PARAMETERS=`cat ${PARFILE} |grep -v "^#"|grep -v "^ "|nawk -F= '{print $1}'`


	for i in $PARLIST
	do
		if ! `echo $PARAMETERS |grep $i > /dev/null `; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
		        "validate: %s is not set in the parameterfile %s but it is required" \
			"${i}" "${PARFILE}"
			rc_validate=1
		fi
	done	

	# test the semantic of the parameters

	. ${PARFILE}

	for i in `cat ${PARFILE} |grep -v "^#"|grep -v "^ "|nawk -F= '{print $1}'`
	do
		case $i in

                        User)

			# Test N1 Grid Service Provisioning System user
                      
                        if [ -z "$User" ]; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate: User is not set but it is required"
				rc_validate=1
                        else
				id ${User} >/dev/null 2>&1
				if [ $? -ne 0 ]; then
	   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
	                                "validate: User %s does not exist but it is required" \
					"${User}"
					rc_validate=1
	                        fi
                        fi;;

                        Basepath)

			# Test N1 Grid Service Provisioning System basepath 
                      
                        if [ -z "$Basepath" ]; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate: Basepath is not set but it is required"
				rc_validate=1
                        else
	                        if [ ! -f ${Basepath}/server/bin/cr_server ]; then
	   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
	                                "validate: The N1 Grid Service Provisioning System start command does not exist, its not a valid masterserver installation"
					rc_validate=1
	                        fi
	                        if [ ! -d $Basepath ]; then
	   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
	                                "validate: Directory %s does not exist" \
					"${Basepath}"
					rc_validate=1
	                        fi
                        fi;;

                        Host)

			# Test N1 Grid Service Provisioning System testhost
                      
                        if [ -z "$Host" ]; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate: Host is not set but it is required"
				rc_validate=1
                        else
				grep -w $Host /etc/hosts >/dev/null 2>&1
	                        if [ $? -ne 0 ]; then
	   					scds_syslog -p daemon.err -t $(syslog_tag) -m \
	                               "validate: Host %s is not found in /etc/hosts but it is required" \
					"${Host}"
					rc_validate=1
	                        fi
                        fi;;


                        Tport)

			# Test N1 Grid Service Provisioning System Tomcat Port
                      
                        if [ -z "$Tport" ]; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate: The Tomcat port is not set but it is required"
				rc_validate=1
                        fi;;

                        TestCmd)

			# Test N1 Grid Service Provisioning System Test Command
                      
                        if [ -z "$TestCmd" ]; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate: TestCmd is not set but it is required"
				rc_validate=1
                        fi;;

                        ReturnString)

			# Test N1 Grid Service Provisioning System Returnstring
                      
                        if [ -z "$ReturnString" ]; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate: Return String is not set but it is required"
				rc_validate=1
                        fi;;

                        Startwait)

			# Test N1 Grid Service Provisioning System Startwait Option
                      
                        if [ -z "$Startwait" ]; then
   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                "validate: Startwait is not set but it is required"
				rc_validate=1
                        fi;;

                        WgetPath)

			# Test N1 Grid Service Provisioning System WgetPath Option
                      
                        if [ -n "$WgetPath" ]; then
				if [ ! -f $WgetPath ]; then
	   				scds_syslog -p daemon.err -t $(syslog_tag) -m \
                                	"validate: The command wget is not fund under %s" \
					"$WgetPath"
					rc_validate=1
				fi
                        fi;;

                        *)

			# All other Variables are invalid
                      
   			scds_syslog -p daemon.err -t $(syslog_tag) -m \
                        "validate: An invalid option entered or # is not the first character"
			rc_validate=1
                       ;;
		esac
	done

	debug_message "Function: validate - End"

	return ${rc_validate}

}

tomcat_connect()
{
	#
	# connect to tomcat mconnect or wget, depending on the WgetPath variable
	#

        debug_message "Function: tomcat_connect - Begin"
	$SET_DEBUG

	rc_tomcat_connect=0

	if [ -z "$WgetPath" ]
	then

		# use mconnect for http

		mconnect -p ${Tport} ${Host} 2>&1 << EOF|egrep "${ReturnString}" >/dev/null  
${TestCmd}
EOF
		rc_tomcat_connect=$?
	else

		# use wget for https

		${WgetPath} -O - https://${Host}:${Tport}${TestCmd} 2>/dev/null |egrep "${ReturnString}" >/dev/null
		rc_tomcat_connect=$?
	fi

        debug_message "Function: tomcat_connect - end"
	return ${rc_tomcat_connect}
}

start_spsma()
{
	#
	# Start N1 Grid Service Provisioning System
	#

        debug_message "Function: start_spsma - Begin"
	$SET_DEBUG

	# remove shared all the memory segments whitout attached processes

	Remove_shared_memory $User

        # Get the project name for the resource

        srm_function $User

        if [ $? -ne 0 ]; then
                # The error message is out of by the function
                exit 1
        fi


	#
	# This should take care of sh, ksh, csh, tcsh and bash
	#

	if [ -z "${SMF_FMRI}" ]
	then
		if getent passwd ${User} | awk -F: '{print $7}' | grep csh > /dev/null
		then
			su - ${User} -c "$TASK_COMMAND ${Basepath}/server/bin/cr_server start noprompt >& ${LOGFILE}" > /dev/null
			rc_start_command=$?
		else
			su - ${User} -c "$TASK_COMMAND ${Basepath}/server/bin/cr_server start noprompt >${LOGFILE} 2>&1" > /dev/null
			rc_start_command=$?
		fi
	else
		${Basepath}/server/bin/cr_server start noprompt >${LOGFILE} 2>&1
		rc_start_command=$?
	fi

	sleep $Startwait

	debug_message "Function: start_spsma - End"

	return ${rc_start_command}
}

stop_spsma()
{
	#
	# Stop N1 Grid Service Provisioning System
	#

        debug_message "Function: stop_spsma - Begin"
	$SET_DEBUG

        # Get the project name for the resource

        srm_function $User

        if [ $? -ne 0 ]; then
                # The error message is out of by the function
                TASK_COMMAND=""
        fi


	#
	# This should take care of sh, ksh, csh, tcsh and bash
	#

	if [ -z "${SMF_FMRI}" ]
	then
		if getent passwd ${User} | awk -F: '{print $7}' | grep csh > /dev/null
		then
			su - ${User} -c "$TASK_COMMAND ${Basepath}/server/bin/cr_server stop >& ${LOGFILE}" > /dev/null
			rc_stop_command=$?
		else
			su - ${User} -c "$TASK_COMMAND ${Basepath}/server/bin/cr_server stop >${LOGFILE} 2>&1" > /dev/null
			rc_stop_command=$?
		fi
	else
		${Basepath}/server/bin/cr_server stop >${LOGFILE} 2>&1
		rc_stop_command=$?
	fi

	debug_message "Function: stop_spsma - End"

	return ${rc_stop_command}
}

check_spsma()
{

	# 
	# Probe N1 Grid Service Provisioning System
	#

        debug_message "Function: check_spsma - Begin"
	$SET_DEBUG

	rc_check_command=0

	# determine, wether the start command is running, this indicates that the probe is fired during
	# wait for online algorythm of the gds

	# if wait_for_online will be set to 1 no diagnostic message will be dropped to syslog

	wait_for_online=0

	# check for the gds_svc_start program under root

	ps -u root -o args|grep -v grep |grep gds_svc_start |grep -w $RESOURCE >/dev/null

	if [ $? -eq 0 ]; then
		wait_for_online=1
	fi 

	# test if monitor host is reachable

	/usr/sbin/ping ${Host} 2 >/dev/null
	rc_ping_command=$?

	# test if Tomcat is operational

	if [ $rc_ping_command -eq 0 ]; then
		tomcat_connect
		if [ $? -ne 0 ]
		then

			if [ $wait_for_online -eq 0 ]; then

	# drop a message for the first probe

       		         	scds_syslog -p daemon.notice -t $(syslog_tag) -m \
               		 	"first probe for N1 Grid Service Provisioning System Tomcat was unsuccessful, try again in 5 seconds" 
			fi

			sleep 5

	# try again

			tomcat_connect
			if [ $? -ne 0 ]; then
				if [ $wait_for_online -eq 0 ]; then

	# drop a message for that Tomcat is unavailable

                			scds_syslog -p daemon.notice -t $(syslog_tag) -m \
                			"last probe for N1 Grid Service Provisioning System Tomcat failed, N1 Grid Service Provisioning System considered as unavailable" 
				fi
				rc_check_command=1
			fi
		fi
	else
		rc_check_command=1
	fi
	
	# if Tomcat does not work return 1 and stop this probe

	if [ $rc_check_command -ne 0 ]; then 
		return $rc_check_command
	fi


	# Start the database probe
	
	Dbuser=sc_test
	Dbtable=sc_test
        ROXDBCMD=${Basepath}/server/bin/roxdbcmd
        ROXDBTRUNC="truncate $Dbtable"
        ROXDBINS="insert into $Dbtable (sccol) values('hello im there')"
        ROXDBSEL="select * from $Dbtable"

	# setting the environment for the database probe

	. $ROXDBCMD
	
	# truncate and fill the table and check for the test value

	psql -d rox -U $Dbuser -c "$ROXDBTRUNC;$ROXDBINS;$ROXDBSEL" |grep hello >/dev/null
	if [ $? -ne 0 ]; then
		if [ $wait_for_online -eq 0 ]; then

	# drop a message for that the Database System is unavailable

        		scds_syslog -p daemon.notice -t $(syslog_tag) -m \
               		"The N1 Grid Service Provisioning System database is unavailable or the test user %s or the test table %s is not set up correct"  \
			"${Dbuser}" "${Dbtable}"
		fi
		rc_check_command=1
	fi

	debug_message "Function: check_spsma - End"
	
	return ${rc_check_command}
}
