#!/bin/sh
#
# Copyright (c) 2002-2004 by Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
#ident "@(#)prepatch 1.0 - 02/10/23"

# Check to see if the admin and directory server are running or configured. 
#

stop_patch=no
cmd_torun_admin=

# Admin server first

debug() {
    if [ "x"$VERBOSE != "x" ] ; then
	echo $1
    fi
}

get_pkgname() {
    debug "get_pkgname $1"
    PKG=$1
    pkginfo -R $ROOTDIR $PKG.\* 1>/dev/null 2>&1
    if [ $? -ne 0 ]; then
	debug "No package $1 installed"
	return 1
    else
	PKGNAME=`pkginfo -R ${ROOTDIR} $1.\* | awk '{print $2}'`
    fi
    debug "get_pkgname returns $PKGNAME"
    return 0
}

get_basedir() {
    debug "get_basedir $1"    
    get_pkgname $1
    if [ $? -ne 0 ]; then
	return 1
    else
	LOCAL_BASEDIR=`pkginfo -R ${ROOTDIR} -r $PKGNAME`
	if [ ${ROOTDIR} != '/' ] ; then
	    PKGBASEDIR=${ROOTDIR}/${LOCAL_BASEDIR}
	else
	    PKGBASEDIR=${LOCAL_BASEDIR}
	fi
    fi
    debug "get_basedir returns $PKGBASEDIR"
    return 0
}

#########################################

#####################################
#
# Setup the variables for AS and DS 
#
#####################################

# For AS

get_basedir SUNWasvu
AS_BASEDIR=${PKGBASEDIR}

# For DS

get_basedir SUNWdsvu
DS_LOCAL_BASEDIR=${LOCAL_BASEDIR}

if [ -f ${AS_BASEDIR}/etc/mps/admin/v5.2/shared/config/serverroot.conf ] ; then
    SERVER_ROOT=${ROOTDIR}/`cat ${AS_BASEDIR}/etc/mps/admin/v5.2/shared/config/serverroot.conf`
fi

#####################################
#
# stop the ldap instances
#
#####################################

PATHNUM=`env | grep PatchNum`
stop_patch=no
cmd_torun_ds=
instance_list=`ls -d ${SERVER_ROOT}/slapd-* 2>/dev/null`
if [ ! "x${instance_list}" = "x" ]
then
    for i in `ls -d ${SERVER_ROOT}/slapd-*`
    do
	servername=`/bin/basename $i | /bin/awk '{ print substr($0,7,length($0)-6) }'` 
	if [ -f /var/tmp/.shouldRestart_DS_${servername}_${PATHNUM} ]; then
		rm -f /var/tmp/.shouldRestart_DS_${servername}_${PATHNUM}
	fi
	if [ -f ${i}/logs/pid ]
	then
            if [ "x${ROOTDIR}" = "x" ] || [ "x${ROOTDIR}" = "x/" ]
    	    then
           	echo "Prepatch script is stopping Directory Server instance ${i}..."
		cd ${DS_LOCAL_BASEDIR}/usr/ds/v5.2/sbin
		eval ./directoryserver -s ${servername} stop
		if [ $? -eq 1 ];then
			echo "Directory Server instance could not be stopped"
			exit 1
		else
			echo "Directory Server instance stopped"
		fi
        	touch /var/tmp/.shouldRestart_DS_${servername}_${PATHNUM}
            else
		stop_patch=yes
		cmd_torun_ds="${cmd_torun_ds} ${DS_LOCAL_BASEDIR}/usr/ds/v5.2/sbin/directoryserver -s ${servername} stop\n"
    	    fi
	fi
    done
fi

if [ ${stop_patch} = yes ]
then
	echo "You must stop the servers before applying this patch."
	echo "Log in to the system where this patch is to be"
	echo "installed and run the following commands:"
	echo ${cmd_torun_admin}
	echo ${cmd_torun_ds}
	exit 1
fi

