#!/bin/ksh
#
# Copyright 2002,2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# Check the status of SAP xserver and liveCache.
# Input: command to use to probe xserver and livecache
#	 (eg. /sapdb/programs/bin/dbmcli)
# Input: livecache name
# Input: logical host name for livecache resource
#
# Output	1: xserver is up
#		2: xserver is down
#		3: xserver is up, LC is online (WARM, ONLINE starting with
#			version 7.4.2)
#		4: xserver is up, LC not found (wrong LC-NAME)
#		11: livecache parent process not found
#		10: usage error
#		12: dbmcli command failed
#
#pragma ident	"@(#)check_db_state.ksh	1.4	05/10/17 SMI"

EGREP="/usr/bin/egrep"

if [ $# = 3 ]; then
	CMD=$1
	LC_NAME=$2
	HOST_NAME=$3
else
	print "Invalid Invocation."
	print "Usage: $0 <DBMCLI> <LC_NAME> <LH_HOSTNAME>"
	exit 10
fi

OUT=`$CMD -d $LC_NAME -n $HOST_NAME db_state`

if [[ `echo $OUT|$EGREP -c 'x_server not running'` -gt 0 ]]; then
	exit 2
# nout found is not a typo
elif [[ `echo $OUT|$EGREP -c 'database or server nout found|database or
server not found'` -gt 0 ]]; then
	exit 4
elif [[ `echo $OUT|$EGREP -c 'ONLINE|WARM'` -gt 0 ]]; then
	if [ ! -f /var/spool/sql/ppid/$LC_NAME ]; then
		exit 11
	else
		parent_id=`cat /var/spool/sql/ppid/$LC_NAME`
		ps -ef | grep  $parent_id | grep -v grep > /dev/null
		rc=$?
		if [[ $rc -ne 0 ]]; then
			exit 11
		else	
			exit 3
		fi
	fi
elif [[ `echo $OUT|$EGREP -c 'OK'` -gt 0 ]]; then
	exit 1
fi

# dbmcli command failed
exit 12
