#! /bin/sh
#
#	Copyright 04/30/99 Sun Microsystems, Inc.  All Rights Reserved.
#
#pragma ident       "@(#)oserv_start.sh 1.8     00/08/25 SMI"
#
# oserv_start -- start the Tivoli server or client oserv
# Called by tivoli_svc_start_net method.
#
# Usage: oserv_start <bindir> <libdir> <logical host> <port> <dbdir>

bindir=$1/solaris2
libdir=$2/solaris2
lhost=$3
port=$4
dbdir=$5

# Need to set WLOCAL host variable if -H option is to be omited.
WLOCALHOST=$lhost
export WLOCALHOST

PATH="$bindir/bin:$PATH"
export PATH

# specifying -B option to oserv is not enough; LD_LIBRARY_PATH must be exported:
LD_LIBRARY_PATH="${libdir}:/usr/openwin/lib:/usr/lib:/usr/ucblib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export LD_LIBRARY_PATH

grep "^\$TREV" $bindir/bin/wsupport | grep "3.6" > /dev/null 2>&1
if [ $? -eq 0 ]
then
  TIVOLI_VERSION=3.6
else
  TIVOLI_VERSION=3.2
fi

#
# The Tivoli client oserv will not successfully start up
# before Tivoli server oserv has started up, so we loop.
#

i=0
while true; do
	# exit if oserv is running already
# -H option is a Tivoli v3.2 feature, not supported in v3.6.
	if [ ${TIVOLI_VERSION} = "3.2" ]
	then
		ps -ef | grep -w oserv | grep "H $lhost " > /dev/null 2>&1
	else # 3.6
		# To avoid grep fail due to long dbdir
		tmp_dbdir=`echo $dbdir | cut -b1-60`
		ps -ef | grep -w oserv | grep "k $tmp_dbdir" > /dev/null 2>&1
	fi
	if [ $? -eq 0 ] ; then
		exit 0
	fi 

	if [ ${TIVOLI_VERSION} = "3.2" ]
	then
		# if port is busy, wait until it is free
		servicename=`grep "[ 	]${port}/tcp" /etc/services | awk '{print $1}'`
		servicename=${servicename:-$port}
		netstat -a | awk '{print $1}' | awk -F. '{if ($1 == "$lhost") {print $NF}}' | grep -w $servicename
#		netstat -an | awk '{print $1}' | awk -F. '{print $5}' | grep -w $port
		if [ $? -eq 0 ] ; then
			sleep 3
			continue
		fi 
	fi 

# -H option is a Tivoli v3.2 feature, not supported in v3.6.
	if [ ${TIVOLI_VERSION} = "3.2" ]
	then
		oserv -H $lhost -p $port -k $dbdir > /dev/null 2>&1
	else # 3.6
		oserv -p $port -k $dbdir > /dev/null 2>&1
	fi
	if [ $? -eq 0 ]; then
		exit 0
	fi
	i=`expr $i + 1`
	if [ $i -lt 20 ]; then
		sleep 3
		continue
	fi
	# We've tried for a minute; give up now.
	exit 1
done
