#!/sbin/sh

#pragma ident "@(#)ora_check.sh	1.2 95/05/02 Sun Microsystems, Inc."

#
#  ora_check - checks whether or not oracle instances are running.
#

PROG=`basename $0`
HOST=`cat /etc/nodename`
B=/opt/SUNWcluster/bin
E=/etc/opt/SUNWcluster
V=/var/opt/SUNWcluster
LOG=${B}/log_info
RM="/bin/rm"
GREP=/bin/grep
AWK=/bin/awk
CAT=/bin/cat
PS=/usr/bin/ps
INIT="FALSE"

ORACLE_NAME="ora_pmon"

# get program options
set -- `getopt ie $*`

for i in  $*
do
	case $i in
	-i) INIT="TRUE"; shift ;;
	-e) ECHOSTATE="TRUE"; shift ;;
	--) shift; break;;
	esac
done

if [ -f ${E}/conf/default_clustername ]; then
	CLUSTNAME=`${CAT} ${E}/conf/default_clustername`
else
	echo "${PROG}: ERROR, cluster name not found, is SUNWpdbconf installed?"
	exit 1
fi

STATEFILE=${V}/${CLUSTNAME}/oracle.state

up_message() {
	if [ "${ECHOSTATE}" = "TRUE" ]; then
		echo "ora: up"
	else
		echo "1" > ${STATEFILE}
		${LOG} "SUNWcluster.oracle.6010" \
			"node ${HOST} has oracle instances running"
		if [ ! -f ${STATEFILE} ]; then
			/usr/ucb/logger -p local0.error -t "${PROG}" \
				"ERROR, couldn't create ${STATEFILE}"
		fi
	fi
}

down_message() {
	if [ "${ECHOSTATE}" = "TRUE" ]; then
		echo "ora: down"
	else
		echo "0" > ${STATEFILE}
		${LOG} "SUNWcluster.oracle.5010" \
			"node ${HOST} has no oracle instances running"
		if [ ! -f ${STATEFILE} ]; then
			/usr/ucb/logger -p local0.error -t "${PROG}" \
				"ERROR, couldn't create ${STATEFILE}"
		fi
	fi
}

ORACLE_PID=`${PS} -ef | ${GREP} ${ORACLE_NAME} |
			${GREP} -v grep | ${AWK} '{print $2}'`

if [ "${INIT}" = "TRUE" ]; then
	${RM} -f ${STATEFILE}
fi

if [ ! -f ${STATEFILE} -o "${ECHOSTATE}" = "TRUE" ]; then
	# statefile not present, create it and report state
	if [ -n "${ORACLE_PID}" ]; then
		up_message
	else
		down_message
	fi
else
	# statefile present
	CURSTATE=`${CAT} ${STATEFILE}`

	if [ -n "${ORACLE_PID}" ] ; then
		# oracle present, was it down before
		if [ "${CURSTATE}" = "0" ] ; then
			# yes, report state change
			up_message
		fi
	else
		# oracle not present, was it up before
		if [ "${CURSTATE}" = "1" ] ; then
			# yes, report state change
			down_message
		fi
	fi
fi

exit 0
