#!/usr/bin/sh
# Copyright 03/20/01 Sun Microsystems, Inc. All Rights Reserved.
#pragma ident  "@(#)em_services	1.202 01/03/20 Sun Microsystems"

#

###############################################################################
# em_services
###############################################################################
#
# Start/stop Solstice EM MIS services.
#
###############################################################################

###############################################################################
# errmsg
###############################################################################
#
# Echo arguments.
#
###############################################################################

errmsg()
{
    if [ "$1" = "-n" ] ; then
	shift
	gettext em_services "$*"		# no newline
    else
	gettext em_services "$*\\n"
    fi
}

###############################################################################
# Environment
###############################################################################
#
# Set up the environment.
#
###############################################################################

trap 'errmsg "\\nem_services terminated."; exit 1' 1 3 15
trap 'interrupt' 2

#
# To debug, switch the shell to ksh and uncomment out the following.
#
# single_step()
# {
#     echo "${PS2}\c"
#     read
# }
# 
# set -x
# trap 'single_step' DEBUG

umask 002					# make it something sane

#
# Set local variables.  These variables control the behavior of em_services.
#

# Number of sink processes for eds. On large mp systems set this to
# be equal to number of processers - 1
numsinks=4

#
# Required diskspace for $EM_RUNTIME in KB.  If $EM_RUNTIME doesn't have
# this much free space, the database won't be created.  To change, run
# em_services init to get a virgin database then run du -sk $EM_RUNTIME
# to see what the minimum required diskspace is.
#

required_diskspace=73000

#
# If $EM_RUNTIME has a capacity >= diskspace_threshold, a warning is
# generated.  diskspace_threshold is the percentage free.
#

diskspace_threshold=98

#
# This variable controls the amount of time em_services will wait for the
# MPAs to finish initializing.  The unit is seconds.
# If 0 is specified, it means wait forever.
#

mpa_timeout=0


#
# Set environment variables.
#

if /usr/bin/pkginfo -q SUNWemmis; then
	installdir=`/usr/bin/pkgparam SUNWemmis BASEDIR`
	. $installdir/SUNWconn/em/bin/emenv.sh
	export PATH  # bug in emenv.sh, it does not export PATH
fi

SYSTEMID=`${EM_HOME}/bin/get_local_host`; export SYSTEMID
RESTARTDIR=$EM_HOME/install/em_platform

#
# Set path to java

JAVA_HOME=`/usr/bin/pkgparam SUNWj3rt BASEDIR`/j2se
CLASSPATH=$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:

export JAVA_HOME CLASSPATH

#
# Make sure the daemons started by em_services connect to the MIS we start.
# The user may have EM_SERVER set to another host.
#

EM_SERVER=$SYSTEMID; export EM_SERVER

#
# work from EM_HOME
#

if [ -d $EM_HOME ]; then
    cd $EM_HOME 
fi

#
# Figure out which database we're using.
#

if [ -f $EM_RUNTIME/conf/EM-config ]; then

    if [ -z "$EM_DB_SERVER_TYPE" ] ; then
        found=`grep -s EM_DB_SERVER_TYPE $EM_RUNTIME/conf/EM-config`
        EM_DB_SERVER_TYPE=`echo $found | sed -e 's/[   ]*EM_DB_SERVER_TYPE[    ]*:[    ]*//'`
    fi

    if [ "$EM_DB_SERVER_TYPE" != "informix" -a \
	 "$EM_DB_SERVER_TYPE" != "DBM" -a \
	 "$EM_DB_SERVER_TYPE" != "OCI" ] ; then
        EM_DB_SERVER_TYPE=informix
    fi
else
    EM_DB_SERVER_TYPE=informix
fi

export EM_DB_SERVER_TYPE 

#
# Load functions specific to the database we're using.
#

# if whitebox; then
#     . ${EM_HOME}/bin/${EM_DB_SERVER_TYPE}/db_services
# elif blackbox; then...

. ${EM_HOME}/bin/db_services


###############################################################################
# interrupt  
###############################################################################
#
# When the user interrupts em_services, ask him what he wants to do.
#
###############################################################################

interrupt()
{
    # put monitor on hold
    cp /dev/null /tmp/emha_hold

    errmsg '\n\nem_services interrupted.  What would you like to do?\n'
    errmsg '	c	continue'
    errmsg '	d <opt>	start em_debug with options <opt> and continue'
    errmsg '	q	quit without changing state (default)'
    errmsg '	s	stop all EM processes and quit'
    errmsg -n '\n> '
    read answer options
    
    # Remove hold on monitor
    rm -f /tmp/emha_hold

    case "$answer" in
	c) 
	    errmsg 'Continuing...'
	    return
	    ;;

	d)
	    errmsg -n "Starting em_debug "
	    errmsg "$options..."
	    eval em_debug $options &
	    return
	    ;;

	s)
            rm -f /tmp/emha_startup
	    errmsg 'Shutting down EM...'
	    kill_procs -HUP
	    exit 2
	    ;;

	*)
	    errmsg 'Quitting...'
	    exit 2
	    ;;
    esac
}



###############################################################################
# info  
###############################################################################
#
# Echo the arguments only if the -q option hasn't been given. All errors 
# should be displayed using echo.  Use info only for informative messages.
#
###############################################################################

info() 
{
    if [ "$1" = "-n" ] ; then
	shift
	gettext em_services "$*" > $display_device 2>&1		# no newline
    else
	gettext em_services "$*\\n" > $display_device 2>&1
    fi
}



###############################################################################
# debugmsg  
###############################################################################
#
# Echo the arguments only if the -d option hasn't been given. 
#
###############################################################################

debugmsg()
{
    if [ "$1" = "-n" ] ; then
	shift
	gettext em_services "$*" > $debug_device 2>&1	# no newline
    else
	gettext em_services "$*\\n" > $debug_device 2>&1
    fi
}


###############################################################################
# progress
###############################################################################
#
# Mark the passage of time to convince the user we haven't really hung at all.
#
###############################################################################

progress()
{
    # marker for monitor
    cp /dev/null /tmp/emha_progress > /dev/null 2>&1

    if [ "$quiet" = TRUE -o "$debug" = TRUE ] ; then
	return
    fi

    progress_counter=`expr $progress_counter + 1`   
    position=`expr $progress_counter % 4`

    if [ $position -eq 0 ] ; then
	echo '|\b\c'
    elif [ $position -eq 1 ] ; then
	echo '/\b\c'
    elif [ $position -eq 2 ] ; then
	echo '-\b\c'
    else
	echo '\\\b\c'
    fi
}


###############################################################################
# ask_confirm
###############################################################################
#
# Prompt the user with $1.  If they answer anything other than 'y', echo $2 
# and exit.  Note that a -f on the command line is equivalent to automatically
# answering 'y' to all questions.
#
###############################################################################

ask_confirm() 
{
    if [ $force = TRUE ] ; then			# don't bother asking
	return
    fi

    if [ -z "$1" ] ; then
	errmsg -n 'Do you really want to do this (y/n)? '	
    else
	errmsg -n "$1 "
    fi

    read answer

    if [ "$answer" != "y" ] && [ "$answer" != "Y" ] ; then
	if [ -z "$2" ]; then
	    errmsg "No action has been taken."
	else
	    errmsg "$2"
	fi
	exit 1
    fi
}


###############################################################################
# start_purged
###############################################################################
#
# Start the purge daemon if the user so wishes.  This can be a performance
# burden, so you may not wish to always start it.
#
###############################################################################

start_purged()
{
    if [ -f $EM_RUNTIME/conf/EM-config ]; then
	if [ -z "$EM_ENABLEPURGE" ] ; then
	    found=`grep -s EM_ENABLEPURGE $EM_RUNTIME/conf/EM-config`
	    EM_ENABLEPURGE=`echo $found | sed -e 's/[   ]*EM_ENABLEPURGE[    ]*:[    ]*//'`
	fi

	if [ "$EM_ENABLEPURGE" = "TRUE" ] ; then
	    info "Starting em_purged..."
	    em_purged&
	fi
    fi
}


###############################################################################
# start_sem_ldap_access_control
###############################################################################
#
# Start the sem ldap for access control if configured
#
###############################################################################

start_sem_ldap_access_control()
{
    LDAP_CONFIG_FILE=/etc/opt/SUNWconn/em/conf/em_accessldap.cfg
    if [ -f $LDAP_CONFIG_FILE ]; then
        found=`grep -s SEM_LDAP_ENABLED $LDAP_CONFIG_FILE`
        SEM_LDAP_ENABLED=`echo $found | sed -e 's/[   ]*SEM_LDAP_ENABLED[    ]*:[    ]*//'`
        found=`grep -s SEM_LDAP_ADMIN_MIS $LDAP_CONFIG_FILE`
        SEM_LDAP_ADMIN_MIS=`echo $found | sed -e 's/[   ]*SEM_LDAP_ADMIN_MIS[    ]*:[    ]*//'`

	if [ "$SEM_LDAP_ENABLED" = "TRUE" ] ; then
	    if [ "$SEM_LDAP_ADMIN_MIS" = "TRUE" ] ; then
	        debugmsg "Starting em_accessldap in admin mode (LDAP write)..."
	    else
	        debugmsg "Starting em_accessldap (LDAP read-only)..."
	    fi
	fi
	em_accessldap&
    fi
}


###############################################################################
# getpid
###############################################################################
#
# Return the pid(s) of the processes with the given name.  A null string is
# returned if the process isn't running.
#
###############################################################################

getpid()
{
   case $1 in
	em_mpa_sunmc | em_jdmkfwd)
		if [ $1 = "em_mpa_sunmc" ] ; then
	 		pid_file=/var/tmp/em_mpa_sunmc.pid
		elif [ $1 = "em_jdmkfwd" ] ; then
			pid_file=/tmp/jdmk_fwd.pid
		fi
		if [ -r $pid_file ] ; then
			process_pid=`cat $pid_file`
			ps -p $process_pid >/dev/null 2>&1
			if [  $? -ne 0 ] ; then
				process_pid=
			fi
		else
			process_pid=
		fi
		echo $process_pid
		;;

	*)
		ps -e -o pid,args | /usr/bin/grep -v "grep"| /usr/bin/grep -w $1 |  sed -e 's/^  *//' -e 's/ .*//'
		;;	

   esac
}



###############################################################################
# kill_procs
###############################################################################
#
# Kill all the EM daemons.
#
###############################################################################

kill_procs() 
{
    if pkginfo -q SUNWemcgr ; then
	if [ "$debug" = TRUE ] ; then
            $EM_HOME/bin/em_cgw_services -debug -stop -force
	elif [ "$quiet" = TRUE ] ; then
            $EM_HOME/bin/em_cgw_services -quiet -stop -force
	else
            $EM_HOME/bin/em_cgw_services -stop -force
	fi
    fi
    progress
    
    # stop the monitor
    em_monitor -stop

    info "Terminating daemons..."
    progress

    for daemon in em_login em_ncam em_mis em_snmfwd em_autod \
	        em_datad em_nnmpa em_dmuxd em_log2hist em_log em_toposrv \
		em_autoexd em_cmip em_mpa_sunmc em_purged em_srm em_eds em_ns_server \
		em_auxdb em_asn1 em_gdmo var-install em_accessldap
    do
	pid=`getpid $daemon`
    
        for p in $pid ; do
            debugmsg -n "Terminating "
	    debugmsg "$daemon: PID=$p "
	    progress
	    kill $1  $p > $debug_device 2>&1
        done
    done

    progress

    if pkginfo -q SUNWemjme ; then
        # kill jma
        # also defined in native/libs/jma/JmaDispatcherImpl.cc
        #pidfile=/var/tmp/jma.pid
        #if [ -r $pidfile ]; then
        #  pids=`/usr/bin/cat $pidfile`
        #  for p in $pids; do
        #    /usr/bin/kill -s TERM $p >/dev/null 2>&1
        #    /usr/bin/kill -s KILL $p >/dev/null 2>&1
        #  done
        #  /bin/rm -f $pidfile
        #fi
        #/bin/touch $pidfile
        #/bin/chmod 666 $pidfile
	$EM_HOME/bin/jme_services -stop
	progress
    fi

    rm -f /tmp/sysmgr.pids /tmp/dmuxd.pid

    if pkginfo -q SUNWemipa ; then
	/etc/rc2.d/S98ipmpa stop > $debug_device 2>&1
    fi

    if pkginfo -q SUNWemjmk ; then
        debugmsg "Stopping em_mpa_jdmk..."
	/etc/rc2.d/S98jdmkmpa stop > $debug_device 2>&1
    fi

    progress

    # Kill the snmp-trap daemon
    
    if [ -x $EM_HOME/bin/em_trapd ]; then
        $EM_HOME/bin/em_trapd stop 
    fi

    progress

    if pkginfo -q SUNWembc ; then
  	snm_kill -A > $debug_device
    fi

    progress

    kill_database $1
    progress

    # Wait for all the processes to die before exiting the shell
    # If any process is alive wait for 2 seconds before resuming
    # existance check

    info "Waiting..."

    process_is_alive=1
    while [ $process_is_alive -eq 1 ]
    do
        process_is_alive=0
        # Assumption : All the processes checked in this loop donot restart
        # after dying
        for daemon in em_monitor em_login em_ncam em_mis em_snmp-trap \
		em_snmfwd em_autod em_datad em_nnmpa em_dmuxd em_log2hist \
		em_log em_toposrv em_autoexd em_purged em_auxdb em_mpa_sunmc \
		em_accessldap
        do
            pid=`getpid $daemon`
            if [ -n ""$pid ] ; then
                process_is_alive=1
                progress
                break
        fi
        done
        sleep 2
    done

    info "Done"

}


###############################################################################
# stat_procs
###############################################################################
#
# Display the process status.
#
###############################################################################

stat_procs() 
{
    for daemon in em_login em_ncam em_mis em_snmp-trap em_snmfwd em_autod \
	          em_datad em_nnmpa em_eds em_srm em_mpa_snmp em_mpa_rpc em_mpa_sunmc\
		  em_log2hist em_log em_autoexd em_ns_server oninit em_cmip \
		  em_accessldap em_purged em_mpa_jdmk em_jdmkfwd em_toposrv jme_jre em_monitor
    do
		pid=`getpid $daemon`
		if [ -z "$pid" ] ; then
           errmsg -n "$daemon:" | awk '{ printf "%-15s ", $1 }'
		   errmsg "not running"
		else
		    for p in $pid ; do
                echo "$daemon:\tPID=$p " | awk '{ printf "%-15s %s\n", $1, $2 }'
		    done
		fi
    done
   	 
    if pkginfo -q SUNWemcgr ; then
	if [ "$debug" = TRUE ] ; then
            $EM_HOME/bin/em_cgw_services -debug -status
	else
            $EM_HOME/bin/em_cgw_services -status
	fi
    fi

   # Status of HA resources
   if pkginfo -q SUNWscr ; then
      for grp in `scha_cluster_get -O all_resourcegroups` ; do
         for res in `scha_resourcegroup_get -O resource_list -G $grp`; do
            if [ "SUNW.emha" = `scha_resource_get -O type -R $res` ] ; then
               break 2
            fi
         done
      done
      echo
      echo "SEM HA resource status:"
      for res in `scha_resourcegroup_get -O resource_list -G $grp` ; do
         state=`scha_resource_get -O resource_state -R $res | nawk '
               $1 ~ "^ONLINE" { print "online"; exit }
                              { print $1 }'`
         echo "$res:\t$state"
      done
   fi

}


###############################################################################
# drop_dbm
###############################################################################
#
# Delete all the DBM files.
#
###############################################################################

drop_dbm()
{
    rm -rf ${EM_RUNTIME}/data/DBM
    rm -rf ${EM_RUNTIME}/data/LOG
    rm -rf ${EM_RUNTIME}/data/EM.DBM
}


###############################################################################
# reinit_platform
###############################################################################
#
# Reinitialize the platform
#
###############################################################################

reinit_platform()
{
    info "Running reinitialization of platform..."
    progress
    cd $EM_MIS_HOME
    var-install

    if [ $? -ne 0 ] ; then
	errmsg "Reinitialization failed."
	exit 1
    fi

    cd bin
}

###############################################################################
# compose_objects
###############################################################################
#
# compose objects for reload option
#
###############################################################################
compose_objects()
{
#
# For 	1) auto management
# 	2) data collection
# 	3) Access Control initial objects
# 	4) SNM BC object.
#

info "Composing EM objects..."
progress
$EM_HOME/bin/em_compose_poc \
	'"EM AUXILIARY SERVER":auxServerConfigContainer' \
	'"EM AUXILIARY SERVER":cmipMpaServer' \
	'"EM Auto Management":autoManagement' \
	'"EM Auto Management":autoManagementEntry' \
	'"EM Data Collector":dataCollector' \
	'"EM Data Collector":dataCollectorEntry' \
        '"Rec. X.741 | ISO/IEC 10164-9 : 1995":accessControl' \
        '"EM Access Control":emAccessControlRules' \
        '"Rec. X.741 | ISO/IEC 10164-9 : 1995":rule' \
        '"Rec. X.741 | ISO/IEC 10164-9 : 1995":notificationEmitter' \
        '"Rec. X.741 | ISO/IEC 10164-9 : 1995":targets' \
        '"Rec. X.741 | ISO/IEC 10164-9 : 1995":operations' \
        '"Rec. X.741 | ISO/IEC 10164-9 : 1995":initiators' \
        '"Rec. X.741 | ISO/IEC 10164-9 : 1995":aclInitiators' \
        '"EM Access Control":accessControlContainer' \
        '"EM Access Control":groupContainer' \
        '"EM Access Control":targetsContainer' \
        '"EM Access Control":applicationContainer' \
        '"EM Access Control":group' \
        '"EM Access Control":application' \
        '"EM Access Control":applicationFeature' \
        '"EM Access Control":accessUserList' \
        '"EM Access Control":emTargets' \
        '"EM Access Control":emNotificationEmitter' \
        '"EM Operator Actions Document":emOperActionsClass' \
        '"EMPurgeLog":emPurgeLog' \
        '"EM Overload Control":emOverloadControlContainer' \
        '"EM DB AuxObject":emAuxObject' \
		> ${debug_device:-/dev/null} 2>&1

if pkginfo -q SUNWemjmc; then
    progress
    $EM_HOME/bin/em_compose_poc \
    	'"EM User Config":userConfig' \
    	'"EM User Config":configEntry' \
    	'"EM User Config":appletIntegration' \
    	'"EM User Config":appletIntegrationEntry' \
		> ${debug_device:-/dev/null} 2>&1
fi
progress

debugmsg "Loading name bindings..."
$EM_HOME/bin/em_load_name_bindings \
	auxServerConfigContainer-systemNB \
	cmipMpaServer-auxServerConfigContainer \
	autoManagement-emKernel \
	autoManagementEntry-autoManagement \
	dataCollector-emKernel \
	dataCollectorEntry-dataCollector \
        rule-accessControlRules \
        operations-targets \
        notificationEmitter-accessControlRules \
        accessControlContainer-root \
        groupContainer-accessControlContainer \
        targetsContainer-accessControlContainer \
        emAccessControlRules-accessControlContainer \
        applicationContainer-accessControlContainer \
        accessUserList-accessControlContainer \
        group-groupContainer \
        application-applicationContainer \
        applicationFeature-application \
        targets-targetsContainer \
        emTargets-targetsContainer \
        emNotificationEmitter-accessControlContainer \
        emOperActions-system \
        emPurgeLog-system \
        emOverloadControlContainer-systemNB \
        emOverloadController-emOverloadControlContainerNB \
        emAuxObject-emDbInfo \
		> ${debug_device:-/dev/null} 2>&1

if pkginfo -q SUNWemjmc; then
    progress
    $EM_HOME/bin/em_load_name_bindings \
   	userConfig-emKernel \
  	configEntry-userConfig \
  	appletIntegration-userConfig \
  	appletIntegrationEntry-appletIntegration \
		> ${debug_device:-/dev/null} 2>&1
fi

progress

}

###############################################################################
# rebuild_platform_objs
###############################################################################
#
# Rebuild the platform objects
#
###############################################################################

rebuild_platform_objs()
{
STARTDIR=$RESTARTDIR
USER_STARTDIR=$EM_RUNTIME/conf

    info "Running rebuild of platform objects ..."
    progress

if [ "$1" = "reload" ] ; then
    compose_objects
fi

#
# The access control objects must be created before all others, however
# setting up the apps and privileges can go on in parallel for better start-up
# performance.
#

debugmsg "Creating access control objects..."
$EM_HOME/bin/em_objop $STARTDIR/.init_access
progress

(
    ## TEMP fix for MIS race condition

    rm -rf /tmp/EMallaccessstuff
    cat $STARTDIR/init_access_em_apps > /tmp/EMallaccessstuff
    cat $USER_STARTDIR/init_access_user_apps >> /tmp/EMallaccessstuff
    cat $USER_STARTDIR/init_access_privileges >> /tmp/EMallaccessstuff
    $EM_HOME/bin/em_accesscmd -import /tmp/EMallaccessstuff
    rm -rf /tmp/EMallaccessstuff
    #$EM_HOME/bin/em_accesscmd -import $STARTDIR/init_access_em_apps
    #progress
    #$EM_HOME/bin/em_accesscmd -import $USER_STARTDIR/init_access_user_apps
    #progress
    #$EM_HOME/bin/em_accesscmd -import $USER_STARTDIR/init_access_privileges
    #progress
) &

#
# Must dynamically create the init_dbobj file because it
# depends upon the hostname.  
#

debugmsg "Creating database objects..."
DB_CONNECT_NAME=${EM_SERVER}_emdb
cat $STARTDIR/.init_dbobj | \
sed "s/DB_CONNECT_NAME/$DB_CONNECT_NAME/g" >$STARTDIR/init_dbobj
$EM_HOME/bin/em_objop $STARTDIR/init_dbobj
progress

debugmsg "Creating miscellaneous EM objects..."
$EM_HOME/bin/em_objop $STARTDIR/init_platform
progress

debugmsg "Creating simple request objects..."
$EM_HOME/bin/em_objop $STARTDIR/init_simple_requests
progress

    cd bin
}

###############################################################################
# start_procs
###############################################################################
#
# Start the EM daemons.
#
###############################################################################

start_procs()
{
    # Start the monitor
    #cp /dev/null /tmp/emha_startup
    #if [ "$monitor" = TRUE ] ; then
        #debugmsg "Starting em_monitor..."
        #$EM_HOME/bin/em_monitor &
    #fi

    info "Starting daemons..."
    mode=$1
    progress

    #
    # Check the diskspace in $EM_RUNTIME.  If it's close to full, put out a
    # warning.  
    #

    capacity=`df -k $EM_RUNTIME | tail -1 | 	
	      awk '{ print substr($5, 0, length($5) - 1) }'`

    if [ "$capacity" -ge "$diskspace_threshold" ] ; then
	errmsg -n "\\nWarning: "
	errmsg -n "$EM_RUNTIME "
	errmsg -n "is "
	errmsg -n "${capacity}% "
	errmsg "full.\\n"
	ask_confirm 'Start Solstice EM (y/n)?' "Solstice EM not started"
	errmsg "\\n"
    fi

    check_runtime $mode

    if [ $mis_installed = TRUE ] ; then

	rm -f /tmp/sysmgr.pids /tmp/dmuxd.pid

	# Start the db aux server

	debugmsg "Starting em_auxdb.."
	em_auxdb &
	AUXDB_PID=$!

	#
	# In case the database is full, the auto-extend daemon must run
	# before any database app (like the MIS and log server) so it can
	# create another chunk if necessary, otherwise the database app will
	# complain.
	#

	progress
	em_autoexd -config $EM_RUNTIME/conf/em_autoexd.cfg > $debug_device 2>&1
	ret=$?
	while [ $ret -ne 0 ]
	do
		debugmsg "Attempting to restart em_autoexd.."
		sleep 5
		em_autoexd -config $EM_RUNTIME/conf/em_autoexd.cfg > $debug_device 2>&1
		ret=$?
	done
	debugmsg "em_autoexd started successfully."

	progress

	debugmsg "Starting em_ncam..."
	em_ncam&
	progress

	# Before starting thr MIS, check if em_auxdb is runnig - else exit
	ps -p $AUXDB_PID > /dev/null 2>&1
        if [ $? -ne 0 ]; then
		# em_auxdb is not running so we must abort startup
		debugmsg "em_auxdb not running: abort startup"
		kill_procs -ABRT
	        
		exit 1
	fi

	debugmsg "Starting em_mis..."

	#
	# Create the lock file.  When the MIS is done initializing, it'll
	# remove the lock file.
	#

	cp /dev/null /tmp/mis-single-user
	chmod 666    /tmp/mis-single-user

	em_mis -d &
	MIS_PID=$!

	progress

	#
	# To debug the MIS, uncomment the following lines.  When prompted,
	# start the debugger in another window and attach to the MIS, then
	# hit <return> in this window to continue.
	#

	#echo "Start dbx em_mis \c" 
	#getpid em_mis
	#echo "Hit return when ready...\c"
	#read answer

	#
	# Wait for the lock file to be removed.  This tells us the MIS is
	# done initializing.
	#

	while [ -f /tmp/mis-single-user ] ; do
	    ps -p $MIS_PID > /dev/null 2>&1
            if [ $? -ne 0 ]; then
		# mis is not running so we must abort startup
		kill_procs -ABRT
	        
		exit 1
	    fi
	    sleep 5
	    progress
	done

	# Re-check, if MIS has really started or got killed.
	#This is needed because, lockfile will be removed even if the process gets killed by any other reason.
	ps -p $MIS_PID > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		# mis is not running so we must abort startup
		errmsg '\nFAILED to start em_mis!!!...Aborting em_services...\n'
		kill_procs -ABRT
		exit 1
	fi

    cp /dev/null /tmp/emha_startup
    if [ "$monitor" = TRUE ] ; then
        debugmsg "Starting em_monitor..."
        $EM_HOME/bin/em_monitor &
    fi

	debugmsg "Starting em_login..."

	#
	# Create the lock file.  When em_login is done initializing, it'll
	# remove the lock file.
	#

	cp /dev/null /tmp/login-not-ready
	chmod 666    /tmp/login-not-ready

	em_login&
	progress

	#
	# Wait for the lock file to be removed.  This tells us em_login is
	# done initializing.
	#

	while [ -f /tmp/login-not-ready ] ; do
	    sleep 5
	    progress
	done

	if [ $mode = "start" ] ; then
	    rebuild_platform_objs $2
	fi

	#if [ $mode = "restart" ] ; then
	#em_startup_updates
	#fi

        # Here we start the Names Server system.
        cp /dev/null /tmp/ns-not-ready
        chmod 666    /tmp/ns-not-ready
        debugmsg "Starting em_ns_server..."
        em_ns_server &
        # Wait for the lock file to be removed.  This tells us NS is
        # done initializing.
        while [ -f /tmp/ns-not-ready ] ; do
            sleep 5
            progress
        done

	# Here we start the eds system
        debugmsg "Starting eds system ..."

	cp /dev/null /tmp/eds-not-ready
	chmod 666    /tmp/eds-not-ready
	
	em_eds -source &

	while [ -f /tmp/eds-not-ready ] ; do
	    progress
	done

	# Make sure that the source is available
 	progress

	while [ "$numsinks" -gt 0 ] ; do
                cp /dev/null /tmp/eds-not-ready
                chmod 666    /tmp/eds-not-ready

                em_eds &

                while [ -f /tmp/eds-not-ready ] ; do
                        progress
                done
		numsinks=`expr $numsinks - 1`
	done

	if [ $mode = "start" ] ; then
	    em_startup $logs_dropped 
	else
	    em_restart 
	fi

	progress

	if [ -x $EM_HOME/bin/em_snmp-trap ] ; then
	    debugmsg "Starting em_snmp-trap..."
	    em_trapd start &
        fi

	progress
	sleep 5

	if pkginfo -q SUNWemipa ; then
	    debugmsg "Starting em_mpa_rpc..."
            debugmsg "Starting em_mpa_snmp..."
	    /etc/rc2.d/S98ipmpa start_em > $debug_device 2>&1
	fi

	if pkginfo -q SUNWemsmc ; then
	    debugmsg "Starting em_mpa_sunmc..."
		em_mpa_sunmc -start
	fi

	progress

	if pkginfo -q SUNWemjmk ; then
	    debugmsg "Starting em_mpa_jdmk..."
	    /etc/rc2.d/S98jdmkmpa start_em > $debug_device 2>&1
        fi

	progress 

	if pkginfo -q SUNWembc ; then
	    debugmsg "Starting em_snmfwd..."
	    em_snmfwd&
	fi

	if pkginfo -q  SUNWemcpa ; then
	    /etc/rc2.d/S98cmipmpa start_em	> $debug_device 2>&1
	fi

	debugmsg "Starting em_nnmpa..."
	em_nnmpa&
	progress

	start_sem_ldap_access_control

	start_purged

	if pkginfo -q SUNWemjme ; then
            debugmsg "Starting jma..."
	    # exec $JAVA_HOME/bin/sparc/green_threads/jre -cp $EM_HOME/classes \
            # -Dcom.sun.em.server.jma.propertyFile=$EM_HOME/html/globalProperties.txt \
            # com.sun.em.server.jma.JmaDispatcherImpl > $debug_device 2>&1 &

	    $EM_HOME/bin/jme_services -start
	fi

	progress
        if pkginfo -q SUNWemcgr ; then
	    start_option="-start_no_kill"
	    if [ $# = 2 ] ; then
	        if [ $2 = "init" -o $2 = "reload" ] ; then
	            start_option="-init_no_kill"
		fi
	    fi

	    if [ "$debug" = TRUE ] ; then
                $EM_HOME/bin/em_cgw_services -debug $start_option
	    elif [ "$quiet" = TRUE ] ; then
                $EM_HOME/bin/em_cgw_services -quiet $start_option
	    else
                $EM_HOME/bin/em_cgw_services $start_option
	    fi
        fi
	
    else					# MIS not installed
        if [ -x $EM_HOME/bin/em_snmp-trap ] ; then
	    debugmsg "Starting em_snmp-trap..."
	    em_trapd start
        fi

	progress

	if pkginfo -q SUNWemipa ; then
            debugmsg "Starting em_mpa_snmp..."
	    debugmsg "Starting em_mpa_rpc..."
	    /etc/rc2.d/S98ipmpa start_em > $debug_device 2>&1
	fi

    fi
   progress

   if pkginfo -q SUNWemipa ; then
	debugmsg "Waiting for SNMP and RPC MPAs to finish initialization..."
	em_objop -wait $mpa_timeout $RESTARTDIR/mandatory_ip_objects 
   fi

   if [ -x $EM_HOME/bin/em_datad ]; then
        debugmsg "Starting em_datad..."
        $EM_HOME/bin/em_datad&
   fi
   progress

   if [ $mis_installed = TRUE ] ; then
	debugmsg "Starting em_autod..."
	em_autod&
   fi

   if [ -x $EM_HOME/bin/em_srm ]; then
        debugmsg "Starting Simple Requests Server....."
        $EM_HOME/bin/em_srm &
   fi

   rm -f /tmp/emha_startup
}



###############################################################################
# usage
###############################################################################
#
# Print a usage message.
#
###############################################################################

usage()
{
    errmsg ""
    errmsg "em_services starts or stops all the necessary processes to run Solstice"
    errmsg "Enterprise Manager."
    errmsg ""
    errmsg "Usage: em_services <command>"
    errmsg ""
    errmsg "<command> instructs em_services what operation to perform:"
    errmsg ""
    errmsg "-abort    abort the MIS daemons immediately"
    errmsg "-debug    enable debugging"
    errmsg "-force    force the command to work without prompting you for confirmation"
    errmsg "-help     this message"
    errmsg "-init     reinitialize the platform"
    errmsg "-no_monit do not start a monitor process to watch server processes"
    errmsg "-quiet    quiet: suppress all output"
    errmsg "-reload   create the data repository and reinitialize the platform"
    errmsg "-start    restart the MIS daemons in the state in which they were last shutdown"
    errmsg "-status   display the status of the MIS daemons"
    errmsg "-stop     stop the MIS daemons"
    errmsg "-version  to display the current version number"
    errmsg ""
    errmsg "-debug, -force, and -quiet only work in conjunction with another option,"
    errmsg 'for example, "em_services -force -stop".'
    errmsg ""
}


###############################################################################
# main
###############################################################################
#
# The main part of this script.
#
###############################################################################

#
# Check if SUNWemmis is installed.
#

if pkginfo -q SUNWemmis.* ; then
    mis_installed=TRUE
else
    mis_installed=FALSE

    if pkginfo -q SUNWemdmn.* ; then
	errmsg "There are no Solstice Enterprise Manager daemons installed."
	errmsg "Nothing to do; exiting."
	exit 1
    fi
fi

#
# Check that SUNWgdmod was installed 
#

#if pkginfo -q SUNWgdmod.* ; then
#    errmsg "No SUNWgdmod package for GDMO/ASN.1 documents. Exit ... "
#    exit 1
#fi

monitor=TRUE; export monitor

#
# If the SUN Cluster and the HA packages are installed, then check to see
# if the logical host is up
#

EM_HA=FALSE
HOST_OK=TRUE
if pkginfo -q SUNWscr && pkginfo -q SUNWemha; then
   ha_host=`get_local_host`
   if [ $? -eq 0 ]; then
         # Logical host is online, OK to continue
         EM_HA=TRUE
         # turn on the boot flag so that the scripts can be started now
         # absence of the flag means: dont run em's rc2.d scripts at boot
         cp /dev/null /tmp/emha_bootflag
   else 
         # Logical host off line
	 debugmsg "Logical host is offline/disabled; using physical host $ha_host."
         errmsg "$ha_host is not the logical host."
         HOST_OK=FALSE
   fi
fi

export EM_HA

#
# Parse command-line arguments
#

quiet=FALSE; export quiet
force=FALSE; export force
debug=FALSE; export debug
progress_counter=0; export progress_counter

if tty -s ; then
   display_device=/dev/tty
else
   display_device=/dev/console
fi
export display_device

debug_device=/dev/null;  export debug_device

logs_dropped=""			# non-null if the logs have been dropped

#
# In previous versions, no arguments meant to start the MIS.  We're keeping
# this idea for backwards compatability, but the preferred approach is
# em_services start.
#

if [ $# -eq 0 ] ; then
    command="start"
else
    arg=$1
    while [ ! -z "$arg" ] ; do
	case $arg in
	    -abort )
		command=abort
		;;
	    -f | -force )  
		force=TRUE
		;;
	    -q | -quiet )  
		quiet=TRUE
		display_device=/dev/null
		;;
	    -d | -debug )
		debug=TRUE
		debug_device=/dev/tty
		;;
            -no_monit )
                monitor=FALSE
                ;;
	    -i | -init )
		command=init
		;;
	    -r | -reload )
		command=reload
		;;
	    -s | -stop )
		command=stop
		;;
	    -start )
		command=start
		;;
	    -status )
		command=status
		;;
	    -V | -version )
		if pkginfo -q SUNWscr && pkginfo -q SUNWemha; then
	           errmsg -n "Solstice Enterprise Manager (TM) High Availability Version "
                else
	
		   errmsg -n "Solstice Enterprise Manager (TM) "
                fi
		cat $EM_HOME/.version
		errmsg ""
		exit 0
		;;
	    -h | -help | * )
		usage
		exit 2
		;;
	esac
	shift 1
	arg=$1
    done
fi

#
# Check if root user.
#

my_uid=`/usr/xpg4/bin/id -u`

if [ $my_uid -ne 0 -a $my_uid -ne $EM_DB_USER_ID ] ; then
    errmsg "You must be the root user to run em_services."
    exit 1
fi

# if logical host is unavaliable, restrict to stop/abort/status/version.
if [ $HOST_OK != "TRUE" ]; then
   case $command in
       stop | abort | status | version )
   	;;
       * ) 
   	errmsg "Logical host disabled, only stop/abort/status/version options valid."
   	exit 1
   	;;
   esac
fi

force_create

case $command in
    start) 
	kill_procs -HUP
        start_procs restart
	;;

    init)     
	if [ $force = FALSE -a $quiet = FALSE -a \
	     -f $EM_RUNTIME/data/db/rootdbs1 ]; then
	    ask_confirm 'Warning: All current MIS information will be lost.\nDo you want to continue (y/n)? ' 'The MIS has not been altered.'
	fi

	kill_procs -HUP

	if [ $mis_installed = TRUE ] ; then
	    clean_database
	fi

	start_procs start init
	;;

    reload)     
	ask_confirm "Warning: EM's database will be destroyed (if any) and all information \nwill be lost. Do you want to continue (y/n)?: " "EM not reloaded."
        kill_procs -ABRT
	drop_dbm
	# Perf : spawn a shell and execute db init and asn1/gdmo complies
	# in parallel
	(
		create_rdb &
		reinit_platform &
		wait  # sync up
	)
        logs_dropped="-dropped"
	pid=`getpid em_mis`	# fix for bug 4086805
	if [ -n ""$pid ]; then  
	    kill -KILL $pid
	fi
        start_procs start reload
	;;

    stop)	
	ask_confirm 'Do you want to gracefully halt EM (y/n)?: ' 'EM not halted.'
	kill_procs -HUP
	debugmsg "em_services shutdown complete."
	exit 0
	;;

    abort)
	ask_confirm 'Do you want to immediately abort EM (y/n)?: ' 'EM not aborted.'
	kill_procs -ABRT
	debugmsg "em_services abort complete."
	exit 0
	;;

    status)
	stat_procs
	exit 0
	;;

    *) 
	usage
	exit 1
	;;
esac

info "em_services start-up complete."
exit 0
