#
# Copyright 06/08/05 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident  "@(#)start-stop-functions.sh	1.94 05/06/08 Sun Microsystems"
#
#
################################################
# COMMON FUNCTIONS USED BY es-start and es-stop
################################################

# Reports missing component 
# $1 Name of missing component
# Exits after flashing message if continue_flag is not set
component_missing() {
    #echolog ""
    echolog "$1 Component not installed"
    [ $continue_flag -eq 0 ] && echolog "Exiting..." && exit 1
    #echolog ""
}

# Input - None
# Retuens running_instances
# replica of platform instance related code in find_SunMC_proc_status
# that fails to provide status update for gui

get_running_instances_of_platform_agent() {
    # Find platform instances if any ...
    #
    running_instances=""           # Clean up the existing values
    not_running_instances=""
    running_processes=`/usr/bin/ps -ef -o "args" | grep "esd - init" | grep -v grep  | cut -d" " -f4` 2> /dev/null

    if [ -f "${VARDIR}/platform-instances.dat" ] ; then
       list_of_instances=`$XGET ${VARDIR}/platform-instances.dat ControlBlock.instances`
       list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/,/ /g"`
       for each_instance in $list_of_instances
       do
          /usr/bin/echo $running_processes | /usr/bin/grep $each_instance > /dev/null 2>&1
          if [ $? -eq 0 ]; then
             running_instances="$running_instances $each_instance"
          else
             not_running_instances="$not_running_instances $each_instance"
          fi
       done
    fi
    initially_running_instances="$running_instances"
    initially_not_running_instances="$not_running_instances"

}

# Input - None
# Returns - SunMC_server_start_error
#         - started_processes
#         - web_server_start_error
#         - grouping_service_start_error
#         - running_instances
#
find_SunMC_proc_status() {

    # Find if SunMC Java server running or not
    #
    SERVER_PID_FILE="$ESDIR/pid/es-server.pid"
    if [ -r "$SERVER_PID_FILE" ] ; then
       old_server_pid=`/usr/bin/cat  "$SERVER_PID_FILE"  2>/dev/null `
       old_server_pid=`/usr/bin/echo $old_server_pid 2>/dev/null `
       /usr/bin/ps -ep "$old_server_pid" | grep -w "$old_server_pid"  1>/dev/null 2>&1
       SunMC_server_start_error=$?
    else
       SunMC_server_start_error=1
    fi
    
    # Find all other SunMC compoments running 
    #
    started_processes=`/usr/bin/ps -ef -o "args" | grep "esd - init" | grep -v grep` 2> /dev/null

    # Find if web server running or not
    #
    WEBSERVER_PID_FILE="$ESDIR/pid/webserver.pid"
    if [ -r "$WEBSERVER_PID_FILE" ] ; then
       old_server_pid=`/usr/bin/cat  "$WEBSERVER_PID_FILE"  2>/dev/null `
       old_server_pid=`/usr/bin/echo $old_server_pid 2>/dev/null `
       /usr/bin/ps -ep "$old_server_pid" | grep -w "$old_server_pid"  1>/dev/null 2>&1
       web_server_start_error=$?
    else
       web_server_start_error=1
    fi
   
#    /usr/bin/ps -ef | /usr/bin/grep "httpd" | /usr/bin/grep -v "grep" | /usr/bin/grep "symon"  > /dev/null 2>&1
#    web_server_start_error=$?
   
    # Find if grouping service running or not
    #
    SERVICE_PID_FILE="$ESDIR/pid/es-service.pid"

    if [ -r "$SERVICE_PID_FILE" ] ; then
       old_service_pid=`/usr/bin/cat  "$SERVICE_PID_FILE"  2>/dev/null `
       old_service_pid=`/usr/bin/echo $old_service_pid 2>/dev/null `
       /usr/bin/ps -ep "$old_service_pid" | /usr/bin/grep -v "grep" | /usr/bin/grep -w "$old_service_pid"  1>/dev/null 2>&1
       grouping_service_start_error=$?
    else
       grouping_service_start_error=1
    fi    
    
    # Find platform instances if any ...
    #
    running_instances=""           # Clean up the existing values
    not_running_instances=""
    running_processes=`/usr/bin/ps -ef -o "args" | grep "esd - init" | grep -v grep  | cut -d" " -f4` 2> /dev/null
    if [ "$do_all_platform_instances" = "1" -o "$do_platform_instance" = "1" ] ; then
       if [ -f "${VARDIR}/platform-instances.dat" ] ; then
          list_of_instances=`$XGET ${VARDIR}/platform-instances.dat ControlBlock.instances`
          list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/,/ /g"`
          for each_instance in $list_of_instances
          do
             /usr/bin/echo $running_processes | /usr/bin/grep $each_instance > /dev/null 2>&1
             if [ $? -eq 0 ]; then
                running_instances="$running_instances $each_instance"
             else
                not_running_instances="$not_running_instances $each_instance"
             fi
          done
       fi
    fi 

    # Find if database is running
    #
    get_lsnr_and_ora_proc_count > /dev/null 2>&1
    if [ $lcnt -gt 0 -a $scnt -ge 8 ] ; then
       database_start_error=0    
    else
       database_start_error=1
    fi
}
    
    

################################################
# FUNCTIONS USED BY es-start
################################################

#added here, may be necessary to move to common later.
check_java_start() {    
    if [ $do_server -eq 1 -o $do_console -eq 1 -o $do_service -eq 1 ] ; then
        checkJavaOK
        if [ $? -ne 0 ] ; then
            echolog 'You must install a supported JDK before attempting to start this component.'
            exit_SunMC_start "$JAVA_ERROR"               
        fi
    fi
}

# Print usage for es-start
# Input : None
# Returns: None
print_usage_start() {
    /usr/bin/echo ""
    eval /usr/bin/echo "\"`/usr/bin/gettext 'Usage: $PROGNAME -achlYAS [-y instanceName] [ -- args... ]\n   where the options represent:\n'`\""
    /usr/bin/gettext '     a : starts Sun Management Center Agent.\n'
    /usr/bin/gettext '     c : starts Sun Management Center Console.\n         Optionally, maximum heap size could be customized,\n         e.g., ./es-start -c -- -Xmx100m specifies 100 MBytes.\n         as max heap size, Default size is 64m.\n'
	/usr/bin/gettext '     n : start Sun Management Center Console in automated mode. This option needs to be used along with the c option to start the console. Additionally, you need to provide the complete path to the ASCII text file as an argument to n option, having the login details of username password serverhost and serverport.\n'
    /usr/bin/gettext '     h : prints this usage report.\n'
    /usr/bin/gettext '     l : starts Platform Agent.\n'
    /usr/bin/gettext '     y : starts new instance of platform agent.\n'
    /usr/bin/gettext '     Y : starts all instances of platform agents.\n'
    /usr/bin/gettext '     A : starts All Sun Management Center components except the console.\n'
    /usr/bin/gettext '     S : starts Sun Management Center Server and all the server subcomponents.\n'
    /usr/bin/gettext '     args are passed to console or server when started.\n           (for example: es-start -c -- -p 2099).\n\n'
    echo "" 
}

set_start_environment() {

   # Reset start flags
   #

   # Since there is nothing
   # called relocation for start
   # call the temp directory fns
   # with blank parameters.

   remove_temp_directory
   create_temp_directory


   reset_flags_start

   set_commondirs   
   set_basedir

   # Set Registry location
   #
   initializeRegistry
   
   get_SunMC_setup_status
   
   [ $no_server -eq 0 ] && set_db_env
   
   # Call set_xput if agent is setup
   #
   [ $no_agent -eq 0 ]  && set_xput

   cd "$BASEDIR"
   PWD="$BASEDIR"; export PWD
   PROGNAME=$0; export PROGNAME
   IESROOT=$BASEDIR; export IESROOT
   
   L_STARTED=""
   L_FAILED=""

}

# Statrs all Platform instances
# Input : None
# Returns: None
#

start_all_platform_instances () {
    if [ ! -f "${VARDIR}/platform-instances.dat" ] ; then
        return 0
    fi

    echologverbose "Starting all platform instances"

    list_of_instances=""
    list_of_instances=`$XGET ${VARDIR}/platform-instances.dat ControlBlock.instances`
    
    echologverbose 'Instances are $2' "$list_of_instances"
    if [ -z "$list_of_instances" ] ; then
        return 0
    fi
    list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/,/ /g"`

    for each_instance in $list_of_instances
    do
        echologverbose 'Starting platform instance:$2.' "$each_instance"
        es-start.sh $each_instance -q &
    done
}


# starts component
# $1 = flag value
# $2 - component name
# Returns: None
start_proc() {

    # Return status of this function
    proc_status=1

    [ $1 -eq 0 ] && return 0

    if [ "$2" = "agent" -o "$2" = "all_platform_instance" ]; then
       AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
       [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
       unset_env_variables
       ESDIR="$AGENT_ESDIR"
       set_basedir
       #echo DEBUG:agent esdir is "$ESDIR"
    fi
    
    if [ "$2" = "all_platform_instance" ] ; then
        start_all_platform_instances
        proc_status=$?
        return $proc_status
    fi
    
    if [ $2 = "service" ] ; then

        # Fetch service registration port from javaserver.properties file
        #
        service_port="5600"
        if [ -f ${VAROPTDIR}/cfg/javaserver.properties ] ; then
           service_port=`/usr/bin/cat ${VAROPTDIR}/cfg/javaserver.properties | /usr/bin/grep "ServiceRegistryPort" | /usr/bin/cut -f2 -d=`
           [ -z "$service_port" ] && service_port="5600"
        fi

	i=1
        #/usr/bin/gettext "Waiting for service registration...\n"
	while [ $i -lt 50 ] 
	do	
	    /usr/bin/sleep 2
	    #/usr/bin/gettext "Waiting for service registration...\n"
	    is_port_open $service_port
	    [ $? -eq 1 ] && break
	    i=`/usr/bin/expr $i + 1`
	done     
	is_port_open $service_port
	if [ $? -eq 0 ] ; then
	   /usr/bin/gettext "Could not find java server."
	   proc_status=1
	   return $proc_status
	fi
	if [ -f $BASEDIR/classes/base/service/bin/es-service.sh ] ; then
 	   if [ "$quiet_flag" != "1" ] ; then
              ( $BASEDIR/classes/base/service/bin/es-service.sh $ARGUMENT & ) 
           else
	      ( $BASEDIR/classes/base/service/bin/es-service.sh $ARGUMENT & > /dev/null 2>&1 ) 
           fi
	fi
	proc_status=$?
	return $proc_status
    fi

    if [ $2 = "metadata" ] ; then
        ESMODULES=$ESDIR/mdr/modules:mdr/modules
        export ESMODULES
        set_paths
    else
        if [ -n "$ESMODULES" ]
        then
            unset ESMODULES
            set_paths
        fi
    fi

    if [ $2 = "agent" -o $2 = "metadata" ] ; then
	[ -n "$LANG" ] && temp_lang=$LANG
        [ -n "$LC_ALL" ] && temp_lc=$LC_ALL
        LANG=C
        export LANG
        LC_ALL=C
        export LC_ALL
    fi

    if [ $2 = "event" -o $2 = "topology" ] ; then
	#
	# Path to SunMC Database Library
	#
	LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${ORACLE_HOME}/lib
	export LD_LIBRARY_PATH
    fi

    if [ $2 = "hdservice" ] ; then
        HWDS_CMD=`/usr/bin/pkginfo -r SUNWed`/SUNWsymon/addons/AdvancedMonitoring/sbin/start-diag
        if [ -x "$HWDS_CMD" ]; then    
            # Starting the Hardware Diagnostic Suite Service
            $HWDS_CMD  > /dev/null
            #Can not find exit staus of HWDS_CMD
            proc_status=0
        else
            proc_status=1
        fi

        return $proc_status

    fi
    
    if [ $2 = "cstservice" ] ; then
       /usr/bin/pkginfo -qi SUNWcstv
       SUNWcstv_missing=$?
       /usr/bin/pkginfo -qi SUNWcstve
       SUNWcstve_missing=$?
       /usr/bin/pkginfo -qi SUNWcstu
       SUNWcstu_missing=$?
       if [ $SUNWcstu_missing -eq 1 -a $SUNWcstv_missing -eq 1 -a $SUNWcstve_missing -eq 1 ] ; then
          echolog 'Package required to start CST service is missing:$2.' "SUNWcstv/SUNWcstve/SUNWcstu"
          return 1
       fi
    fi
    
    
    # Check presence of security keys. Return if not present ( including platform instances )
    #
    check_security_keys "$2" 
    
    if [ $? -eq 0 ]; then
       if [ $interactive_flag -eq 1 ] ; then
          if [ $quiet_flag -eq 1 ] ; then
	     $BASEDIR/base/bin/es-start.sh $2 -i -q  
          else
             $BASEDIR/base/bin/es-start.sh $2 -i  
          fi
          exit $?
       else
          ( $BASEDIR/base/bin/es-start.sh $2 -q  > /dev/null 2>&1  & )
          proc_status=$?
       fi
    else
       proc_status=1
    fi

    if [ $2 = "agent" -o $2 = "metadata" ] ; then

       if [ -n "$temp_lang" ]; then
          LANG=$temp_lang
       else
          LANG=""
       fi
       export LANG

       if [ -n "$temp_lc" ]; then
          LC_ALL=$temp_lc
       else
          LC_ALL=""
       fi
       export LC_ALL

    fi
    
    if [ "$2" = "agent" -o "$2" = "all_platform_instance" ]; then
       unset_env_variables
       ESDIR="/var/opt/SUNWsymon"
       set_basedir
    fi
    
    return $proc_status
}


# Finds if security keys are present in configuration file or not
# $1 = component name Can be one of the "server trap event cstservice topology cfgserver metadata agent platform"

# Returns : echos a worrning messages & returns 1 if keys cfg file not found.
#
check_security_keys() {
   if [ "$1" = "server" ]; then
      [ ! -f "${VARDIR}/server-global-keys.x" ] &&  echolog 'Security key for $2 is not available.' "java server" && return 1
   else
      [ ! -f "${VARDIR}/${1}-usmusertbl-d.dat" ] && echolog 'Security key for $2 is not available.' "$1" && return 1
   fi
   return 0
}

# Checks setup file exists or not
# $1 = filename to check
# exits if $1 does not exists
# Returns: None
#
check_setup() {

    if [ ! -f "$1" ] ; then
           echolog ""
           echolog "ERROR:Sun Management Center has not been setup."
	   echolog "Run es-setup to set up Sun Management Center."
	   echolog ""
	   exit_SunMC "$BAD_SETUP_ERROR"
    fi

}

# Checks setup file exists or not
# $1 = filename to check
# Returns: 1 on failure else 0
#
check_setup_but_dont_exit () {

    if [ ! -f "$1" ] ; then
           echolog ""
           echolog 'It seems component $2 has not been setup, so skipping it.' "$2"
           echolog ""
           return 1
    fi
    return 0
}


# Starts Web server
# if $1 = "w" then flash a error message.
# Returns: None
#
start_web_server () {
    WEBSERVER_PID_FILE="$ESDIR/pid/webserver.pid"
    if [ -r "$WEBSERVER_PID_FILE" ] ; then
       old_server_pid=`/usr/bin/cat  "$WEBSERVER_PID_FILE"  2>/dev/null `
       old_server_pid=`/usr/bin/echo $old_server_pid 2>/dev/null `
       /usr/bin/ps -ep "$old_server_pid" | grep -w "$old_server_pid"  1>/dev/null 2>&1
       if [ $? -eq 0 ] ; then
          stop_web_server 1>/dev/null 2>&1
       fi
    fi
  
    check_webserver
    if [ $? -ne 0 ] ; then
        if [ "$option" = "w" ]; then
            echolog 'Sun Management Center Web Server is not Installed, Can not start web server.'
            echolog ''
        fi
        return 0
    fi
    
    CATALINA_BASE="$BASEDIR/web"
    
    export CATALINA_BASE

    CATALINA_CLASSPATH="${CATALINA_HOME}/bin/bootstrap.jar"
    [ -f "$JAVA_HOME/lib/tools.jar" ]  && CATALINA_CLASSPATH=${CATALINA_CLASSPATH}:"${JAVA_HOME}/lib/tools.jar"
    [ -f "$JAVA_HOME/jre/lib/jsse.jar" ] && CATALINA_CLASSPATH=${CATALINA_CLASSPATH}:"${JAVA_HOME}/jre/lib/jsse.jar"

    addon_dirs=`/usr/bin/ls -1 $BASEDIR/addons 2>/dev/null`
    if [ ! -z "$addon_dirs" ]; then
        for i in $addon_dirs
        do
           if [ -d $BASEDIR/addons/$i/lib/locale/classes ]; then
               CATALINA_CLASSPATH=${CATALINA_CLASSPATH}:$BASEDIR/addons/$i/lib/locale/classes
           fi
        done
    fi

    # If keystore file does not exist, create it.
    #
    
    /usr/bin/mkdir -p "$VAROPTDIR/web"
    /usr/bin/mkdir -p "$VAROPTDIR/web/logs"
    /usr/bin/rm -f "$VAROPTDIR/web/logs/catalina_log*.txt"
    /usr/bin/rm -f "$VAROPTDIR/web/logs/localhost_log*.txt"

    /usr/bin/touch $VAROPTDIR/web/logs/catalina.out 
    /usr/bin/chown nobody $VAROPTDIR/web/logs/catalina.out 


    KEYSTORE="$VAROPTDIR/web/keystore"
    #KEYSTORE="/etc/keystore"

    if [ ! -f "${KEYSTORE}" ]; then

        O=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "customer_organization" 2> /dev/null `
        L=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "customer_location" 2> /dev/null `
        #
        # It seems command tr has some problem in non C locale (zh for sure).
        # It prints Bad String. See bug id 4742072. I could not find, why
        # is it so. May be the problem in multibyte char handling. The problem
        # is not there in C locale. Just fixing it in safe and non risky way.
        #
        OLD_LANG=$LANG
        OLD_LC_MESSAGES=$LC_MESSAGES
        LANG=C
        export LANG
        LC_MESSAGES=C
        export LC_MESSAGES
        L=`/usr/bin/echo "$L" | /usr/bin/tr -cs "[:alpha:]" "[ *]" `
        O=`/usr/bin/echo $O | /usr/bin/tr -cs "[:alpha:]" "[ *]" `
        LANG=$OLD_LANG
        export LANG
        LC_MESSAGES=$OLD_LC_MESSAGES
        export LC_MESSAGES
        L=`/usr/bin/echo $L `
        O=`/usr/bin/echo $O ` 
        [ -z "$O" ] && O="Unknown"
        [ -z "$L" ] && L="Unknown"
        CN="$O"
       
        ${JAVA_HOME}/bin/keytool -validity 1500 -genkey -alias tomcat -keyalg RSA \
            -keypass changeit -storepass changeit \
            -keystore ${KEYSTORE} \
            -dname "CN=$CN, OU=Sun Management Center, O=$O, L=$L, ST=Unknown, C=Unknown"
        chmod 644 ${KEYSTORE}
    
        unset CN O L 
    fi

    SECURITY_ARGS="-Djava.security.manager -Djava.security.policy==${CATALINA_BASE}/conf/catalina.policy"

    # This will be created in /var/run/tmp - security issue
    DATE_FORMAT=`eval /usr/bin/echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
    TIMESTAMP=`/usr/bin/date $DATE_FORMAT`
    WEBSERVER_CMD="/tmp/web_server_command.$TIMESTAMP.sh"
    WEBSERVER_PID_FILE="/tmp/webserver.pid" # This needs to be created in tmp as it is owned by nobody
                                            # Later moved to ESDIR to keep interface intact
                                            # umask is already set so that this has read write permission to owner only
                                            
    /usr/bin/rm -f $WEBSERVER_CMD
    /usr/bin/echo "#!/bin/sh" > ${WEBSERVER_CMD}

    /usr/bin/echo "/usr/bin/nohup ${JAVA_HOME}/bin/java -classpath ${CATALINA_CLASSPATH} \\" >> ${WEBSERVER_CMD}
    /usr/bin/echo "   ${SECURITY_ARGS} \\" >> ${WEBSERVER_CMD}
    /usr/bin/echo "   -Dcatalina.base=${CATALINA_BASE} -Dcatalina.home=${CATALINA_HOME} \\" >> ${WEBSERVER_CMD}
    /usr/bin/echo "   org.apache.catalina.startup.Bootstrap start \\" >> ${WEBSERVER_CMD}
    /usr/bin/echo "   >> $CATALINA_BASE/logs/catalina.out 2>&1 &" >> ${WEBSERVER_CMD}

    /usr/bin/echo "WEBSERVER_PID=\$!" >> ${WEBSERVER_CMD}
    /usr/bin/echo "/usr/bin/echo \${WEBSERVER_PID} > ${WEBSERVER_PID_FILE}" >> ${WEBSERVER_CMD}

    /usr/bin/chmod 755 ${WEBSERVER_CMD}
    /usr/bin/su - nobody -c "/bin/sh ${WEBSERVER_CMD}" >/dev/null 2>&1
    
    /usr/bin/mkdir -p "$ESDIR/pid"

    # Only root can write to ESDIR
    #
    /usr/bin/cp $WEBSERVER_PID_FILE $ESDIR/pid/ 
    /usr/bin/rm -f $WEBSERVER_PID_FILE 
    /usr/bin/rm -f ${WEBSERVER_CMD}

    /usr/bin/sleep 1
    return 0
}




# Resets/Presets all flags to default values
# Input:None
# Returns:None
#
reset_flags_start() {
 
   interactive_flag=0
   quiet_flag=0
   multi_flag=0
   do_console=0
   do_server=0
   do_trap=0
   do_agent=0
   do_service=0
   do_topo=0
   do_cfg=0
   do_event=0
   do_metadata=0
   do_cstservice=0
   do_platform_instance=0
   do_all_platform_instances=0
   num_comp=0
   do_platform=0
   do_hwds=0
   continue_flag=0
   do_web_server=0
   do_database=0
   VERBOSE=OFF

   server_setup=0
   agent_setup=0
   console_setup=0
   
   service_setup=0
   start_addons_flag=0
   EXIT_STATUS=0
}


# Verifies the ownership of the provided config file
# having the login details. The ownership should be
# the same as the user starting/invoking the console.

verify_ownership() {

    file_name=$1
    login_id=`/usr/bin/id -a|$CMD_CUT -d'(' -f2|$CMD_CUT -d')' -f1` >> /dev/null 2>&1
    /usr/bin/find $file_name -user $login_id -a \( -perm u=r -o -perm u=rw \)| /usr/bin/fgrep $file_name > /dev/null 2>&1
    ret=$?
    if [ ! $ret -eq 0 ] ; then
        echolog 'The file $2 is not owned by the user, or, not read-only. Aborting...' "$file_name"
        exit_SunMC 
    fi

}


# Sets start_flags for es-start according to options selected by user
# $@ - All options provided by user
# Exits if option are wrong
process_options_start() {
   
   if [ $# -eq 0 ] ; then
      /usr/bin/echo ""
      /usr/bin/gettext "You must specify a component to be started."
      print_usage_start
      exit_SunMC_start "$ARGUMENTS_ERROR"
   fi

   called_by_gui=0
   automatic_console=0
   file_name=""
   while getopts y:n:cdgsmatpfexwAShilqvrDGY OPT
   do
      case $OPT in
      c)
          if [ $no_console -eq 1 ] ; then
	      echolog ""
	      echolog "Console package is not Installed. Can not start Console."
	  else
	      if [ $console_setup -eq 0 ] ; then
	          echolog 'Sun Management Center $2 is not Setup.' "Console"
              else
                  do_console=1
              fi
	  fi
	  ;;
	  n)
          if [ $no_console -eq 1 ] ; then
              echolog ""
              echolog "Console package is not Installed. Can not start Console."
          else
              if [ $console_setup -eq 0 ] ; then
                  echolog 'Sun Management Center $2 is not Setup.' "Console"
              else
                  file_name="$OPTARG"
                  if [ ! -z "$file_name" -a "$file_name" != "" ] ; then
                      if [ ! -f "$file_name" ] ; then
                          echolog "Cannot access the given configuration file. Please provide the complete path to the file and try once more.\n"
                          exit_SunMC
                      else
                          verify_ownership $file_name
                          automatic_console=1
                      fi
                  fi
              fi
          fi
          ;;
      d)
         if [ $no_server -eq 1 ] ; then
             echolog 'Sun Management Center Server is not Installed.'
          else
             if [ $no_HA -eq 1 ] ; then
                echolog 'This option is valid in case of HA server only.'
                exit_SunMC_start "$ARGUMENTS_ERROR"
             fi
          fi
          do_database=1
          num_comp=`/usr/bin/expr $num_comp + 1`

          ;;
      s)  if [ $no_server -eq 1 ] ; then
       	      echolog 'Sun Management Center Server is not Installed.'
          else
              if [ $server_setup -eq 1 ] ; then
                  check_root
	          do_server=1
	          #num_comp=`/usr/bin/expr $num_comp + 1`
              else
                  echolog 'Sun Management Center Server is not Setup. You must run es-setup.'
              fi
          fi	    
          num_comp=`/usr/bin/expr $num_comp + 1`

          ;;

      g)  if [ $no_server -eq 1 ] ; then
       	      echolog 'Sun Management Center Server is not Installed.'
          else
              if [ $services_setup -eq 1 ] ; then
                  check_root
                  do_service=1
	          [ $no_HA -eq 1 ] && do_database=1
	          #num_comp=`/usr/bin/expr $num_comp + 1`
              else
                  echolog 'Grouping service is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;

      m)  if [ $no_metadata -eq 1 ] ; then
             echolog 'Sun Management Center Metadata agent is not Installed.'
          else
             if [ $metadata_setup -eq 1 ] ; then
                 check_root
                 do_metadata=1
	         #num_comp=`/usr/bin/expr $num_comp + 1`
             else
                 echolog 'Sun Management Center Metadata service is not Setup.'
             fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;

      a)  if [ $no_agent -eq 1 ] ; then
             echolog 'Sun Management Center Agent is not Installed.'
          else
             if [ $agent_setup -eq 1 ] ; then
                 check_root
                 do_agent=1
	         #num_comp=`/usr/bin/expr $num_comp + 1`
             else
                 echolog 'Sun Management Center Agent is not Setup.'
             fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`

          start_addons_flag=1

          #argument to be passed to addon script -a
          addon_option="-$OPT"
          ;;
      
      t)  if [ $no_server -eq 1 ] ; then
              echolog 'Sun Management Center Server is not Installed.'
          else
              if [ $server_setup -eq 1 ] ; then
                  check_root
                  do_trap=1
                  #num_comp=`/usr/bin/expr $num_comp + 1`
              else
                  echolog 'Sun Management Center Trap handler is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;

      p)  if [ $no_server -eq 1 ] ; then
              echolog 'Sun Management Center Server is not Installed..'
          else
              if [ $server_setup -eq 1 ] ; then
                  check_root
                  do_topo=1
                  [ $no_HA -eq 1 ] && do_database=1
                  #num_comp=`/usr/bin/expr $num_comp + 1`
              else
                  echolog 'Sun Management Center Topology manager is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;
      
      f)  
          if [ $no_server -eq 1 ] ; then
              echolog 'Sun Management Center Server is not Installed..'
          else
              if [ $server_setup -eq 1 ] ; then
                  check_root
                  do_cfg=1
                  #num_comp=`/usr/bin/expr $num_comp + 1`
              else
                  echolog 'Sun Management Center Configuration server is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;
      
      e)
	  if [ $no_server -eq 1 ] ; then
              echolog 'Sun Management Center Server is not Installed.'
          else
              if [ $server_setup -eq 1 ] ; then
                  check_root
                  do_event=1
                  [ $no_HA -eq 1 ] && do_database=1
              else
                  echolog 'Sun Management Center Event handler is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;
      
      x)  
          if [ $no_server -eq 1 ] ; then
              echolog 'Sun Management Center Server is not Installed..'
          else
              if [ $server_setup -eq 1 ] ; then
                  check_root
                  do_cstservice=1
                  #num_comp=`/usr/bin/expr $num_comp + 1`
              else
                  echolog 'Sun Management Center cst service is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;

       w) if [ $no_server -eq 1 ] ; then
              echolog 'Sun Management Center Server is not Installed..'
          else
              if [ $server_setup -eq 1 ] ; then
                 check_root
                 do_web_server=1
                 checkJavaOK
                 start_web_server w
                 #num_comp=`/usr/bin/expr $num_comp + 1`
                 
              else
                  echolog 'Sun Management Center Server is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;
       
       r)
          if [ $no_server -eq 1 ] ; then
              echolog 'Sun Management Center Server is not Installed..'
          else
              if [ $server_setup -eq 1 ] ; then
                 check_root
             	 do_hwds=1
                 #num_comp=`/usr/bin/expr $num_comp + 1`
              else
                  echolog 'Sun Management Center Server is not Setup.'
              fi
          fi
          num_comp=`/usr/bin/expr $num_comp + 1`
          ;;

   A | S)
          if [ "$no_HA" = "0" ]; then
             echolog 'es-start does not apply to Sun Management Center HA setup. Use the startSunMC script to start Sun Management Center.' 
             exit_SunMC "$ARGUMENTS_ERROR"
          fi

          if [ $interactive_flag -eq 1 ] ; then
		echolog ""
		echolog "Interactive option invalid with $OPT option"
		echolog ""
		exit_SunMC "$ARGUMENTS_ERROR"
          fi

          check_root

          if [ $no_server -eq 1 ] ; then 
              echolog 'Sun Management Center Server is not Installed..'
          else

              if [ $server_setup -eq 1 ] ; then
                  do_server=1          # So that check_java_start calls
                                       # checkJavaOK
                  do_web_server=1
                  check_java_start     # if Java OK the second call will
                                       # not give any error
                                       # if Java not OK this will exit here
                  start_web_server A
               
                  do_trap=1
                  do_cfg=1
                  
                  /usr/bin/pkginfo -qi SUNWcstv
                  [ $? -eq 0 ] && do_cstservice=1
	          /usr/bin/pkginfo -qi SUNWcstve
                  [ $? -eq 0 ] && do_cstservice=1
                  /usr/bin/pkginfo -qi SUNWcstu
                  [ $? -eq 0 ] && do_cstservice=1
                  
                  do_event=1
                  do_topo=1
                  #do_server=1
                  do_database=1
                  /usr/bin/pkginfo -qi SUNWed 
                  [ $? -eq 0 ] && do_hwds=1
                  
                  num_comp=`/usr/bin/expr $num_comp + 7`
              else
                  echolog 'Sun Management Center Server is not Setup.'
              fi
 
              if [ $services_setup -eq 1 ] ; then
                 do_service=1
                 num_comp=`/usr/bin/expr $num_comp + 1`
              else
                 echolog 'Sun Management Center Grouping service is not Setup.'
              fi

              if [ $no_metadata -eq 1 ] ; then
                 echolog 'Sun Management Center Metadata agent is not Installed.'
              else
                 if [ $metadata_setup -eq 1 ] ; then
                    do_metadata=1
                    num_comp=`/usr/bin/expr $num_comp + 1`
                 else
                    echolog 'Sun Management Center Metadata service is not Setup.'
                 fi
              fi
          fi
 
          if [ "$OPT" = "A" ] ; then
              if [ $no_agent -eq 1 ] ; then
                  echolog 'Sun Management Center Agent is not Installed.'
              else
                  if [ $agent_setup -eq 1 ] ; then
                      do_agent=1
 	          else
                      echolog 'Sun Management Center Agent is not Setup.'
                  fi
  
                  if [ -f "$VARDIR/platform-usmusertbl-d.dat" ] ; then
	              CONF_FILE=$CONFDIR/symon.conf
		      
		      if [ -f "$CONF_FILE" ] ; then
		          /usr/bin/grep platform "$CONF_FILE" > /dev/null
		          [ $? -eq 0 ] && do_platform=1
		      fi

                  fi
  
                  do_all_platform_instances=1
	      fi
          fi

          multi_flag=1
          #do_database=1
          start_addons_flag=1

          #argument to be passed to addon script - S | A
          addon_option="-$OPT"
          
          ;;

	h)  print_usage_start
	    exit 0
	    ;;

	i)  if [ $multi_flag -eq 1 ] ; then
		echolog ''
		echolog 'Interactive option is invalid with -A, -Y or -S option.'
                exit_SunMC_start "$ARGUMENTS_ERROR"
	    fi
	    interactive_flag=1
	    ;;

	 l)
	    if [ $no_agent -eq 1 ] ; then
                echolog 'Sun Management Center Agent is not Installed.'
            else
                if [ $agent_setup -eq 1 ] ; then
                    check_root
                    if [ -f "$VARDIR/platform-usmusertbl-d.dat" ] ; then
                        CONF_FILE=$CONFDIR/symon.conf
                        if [ -f "$CONF_FILE" ] ; then
                            /usr/bin/grep platform "$CONF_FILE" > /dev/null
                            [ $? -eq 0 ] && do_platform=1
                        fi
                        if [ "$do_platform" != "1" ]; then 
                            do_platform=0 
                            echolog 'Could not locate platform agent configuration.' 
                        fi
                    fi
	            #num_comp=`/usr/bin/expr $num_comp + 1`
                else
                   echolog 'Sun Management Center Agent is not Setup.'
                fi
            fi
            num_comp=`/usr/bin/expr $num_comp + 1`
	    ;;

	 q)
            quiet_flag=1
	    ;;
         v)
	    VERBOSE=ON
	    ;;

         y)
            if [ $no_agent -eq 1 ] ; then
                echolog 'Sun Management Center Agent is not Installed.'
            else
                if [ $agent_setup -eq 1 ] ; then
                     check_root
                     platform_instance_name="$OPTARG"
                     do_platform_instance=1
	             AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
                     [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
                     unset_env_variables
                     ESDIR="$AGENT_ESDIR"
                     set_basedir
	             #num_comp=`/usr/bin/expr $num_comp + 1`
                else
                    echolog 'Sun Management Center Agent is not Setup.'
                fi
            fi
            num_comp=`/usr/bin/expr $num_comp + 1`
	    ;;

         Y)
            if [ $no_agent -eq 1 ] ; then
                echolog 'Sun Management Center Agent is not Installed.'
            else
                if [ $agent_setup -eq 1 ] ; then
                     check_root
                     do_all_platform_instances=1
	             AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
                     [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
                     unset_env_variables
                     ESDIR="$AGENT_ESDIR"
                     set_basedir
                else
                    echolog 'Sun Management Center Agent is not Setup.'
                fi
            fi
            num_comp=`/usr/bin/expr $num_comp + 1`
            multi_flag=1
	    ;;

         G)
	    called_by_gui=1
	    ;;


	\?)
	    print_usage_start
            exit_SunMC_start "$ARGUMENTS_ERROR"
	    ;;
       esac
   done
 
   shift
   
   if [ "$1" = "--" -a $automatic_console -eq 0 ] ; then
      shift
   fi

   ARGUMENT="$*"

   if [ $num_comp -eq 0 ] && [ $multi_flag -eq 0 ] && [ $do_console -eq 0 ] && [ $do_server -eq 0 ] ; then
      echolog ''
      echolog 'You have not specified any valid components to run.'
      exit_SunMC_start "$ARGUMENTS_ERROR"
   fi

   if [ $num_comp -gt 1 ] && [ $interactive_flag -eq 1 ] ; then
       echolog ''
       echolog 'Only one component can be started in interactive mode.'
       exit_SunMC_start "$ARGUMENTS_ERROR"
   fi


   if [ $num_comp -eq 0 ] && [ $do_console -eq 1 ] && [ $interactive_flag -eq 1 ] ; then
      echolog ''
      echolog 'Console can not be started in interactive mode.'
      exit_SunMC_start "$ARGUMENTS_ERROR"
   fi

   if [ $do_service -eq 1 ] && [ $interactive_flag -eq 1 ] ; then
      echolog ''
      echolog 'Grouping service can not be started in interactive mode.'
      exit_SunMC_start "$ARGUMENTS_ERROR"
   fi

   if [ $do_web_server -eq 1 ] && [ $interactive_flag -eq 1 ] ; then
      echolog 'Interactive mode for web server not available. Starting in normal mode...'
   fi
}

do_pre_start_processings() {

   unset_env_variables

   set_paths


   #  Need to start the console first since it is the only one
   #  that cannot run in interactive mode.
   #
   if [ $do_console -eq 1 ] ; then

      if [ -z "$DISPLAY" ] ; then
         echolog ''
         echolog 'DISPLAY environment variable must be set.'
         exit_SunMC_start "$DISPLAY_ERROR"
      fi

      XHOST=/usr/openwin/bin/xhost
      if [ -x $XHOST ] ; then
         $XHOST >/dev/null 2>&1
   
         if [ $? -ne 0 ] ; then
            echolog ''
            echolog 'Unable to open DISPLAY:$2.' "$DISPLAY"
            exit_SunMC_start "$DISPLAY_ERROR"
         fi
      fi
   fi
   
   # flush gui status
   #
   update_initial_gui_start_status
}



# $@ - All options provided by user
# 
#
update_initial_gui_start_status() {
   
   [ "$called_by_gui" != "1" ] && return

   # Only possible switches for GUI wizrd are ASal and y
   #
   GUILOGFILE="$TMP_DIR/start-stop.log"
   /usr/bin/rm -f "$GUILOGFILE"
   /usr/bin/mkdir -p "$TMP_DIR"
   /usr/bin/touch "$GUILOGFILE"

   DONT_L10N_TEXT_INITIAL="GUI_STARTING"
   DONT_L10N_TEXT_SUCCESS="GUI_START_SUCCESS"
   DONT_L10N_TEXT_FAILED="GUI_START_FAIL"

   DONT_L10N_SERVERCOMP="GUI_STARTSTOP_SERVERCOMP"
   DONT_L10N_AGENTCOMP="GUI_STARTSTOP_AGENTCOMP"

   GUI_STATUS_STRING="STATUS="
   
   if [ $do_service -eq 1 ] ; then
          GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ ${DONT_L10N_SERVERCOMP}\
          @ - $DONT_L10N_TEXT_INITIAL JAVA_SERVER\
          @ - $DONT_L10N_TEXT_INITIAL GROUPING_SERVICE\
          @ - $DONT_L10N_TEXT_INITIAL TOPOLOGY_SERVICE\
          @ - $DONT_L10N_TEXT_INITIAL TRAP_SERVICE\
          @ - $DONT_L10N_TEXT_INITIAL CONFIGURATION_SERVICE\
          @ - $DONT_L10N_TEXT_INITIAL EVENTHANDLER_SERVICE\
          @ - $DONT_L10N_TEXT_INITIAL METADATA_SERVICE\
          @ - $DONT_L10N_TEXT_INITIAL WEB_SERVER`"

          /usr/bin/pkginfo -qi SUNWed # Do not display anything about HWDS if not installed.
          if [ $? -eq 0 ]; then
             GUI_STATUS_STRING="$GUI_STATUS_STRING @ - $DONT_L10N_TEXT_INITIAL HARDWARE_SERVICE`"
          fi
   fi

   if [ $do_agent -eq 1 -o $do_platform -eq 1 -o $do_platform_instance -eq 1 ] ; then
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ ${DONT_L10N_AGENTCOMP}"
   fi
   
   if [ $do_agent -eq 1 ] ; then
       #GUI_STATUS_STRING="$GUI_STATUS_STRING @ - $DONT_L10N_TEXT_INITIAL Agent process`"
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL AGENT_PROCESS`"
   fi

   if [ $do_platform -eq 1 ] ; then
      GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL PLATFORM_AGENT`"
   fi

   if [ $do_platform_instance -eq 1 ] ; then
      GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL PLATFORM_INSTANCE $platform_instance_name`"
   fi

   if [ $do_all_platform_instances -eq 1 ] ; then
      list_of_instances=`$XGET ${VARDIR}/platform-instances.dat ControlBlock.instances`
      GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL PLATFORM_INSTANCE $list_of_instances`"
   fi

   /usr/bin/echo "$GUI_STATUS_STRING" | /usr/bin/sed "s/#/\\\t/g" > "$GUILOGFILE"

}



# $1 component to update
# $2 state : 0 started sucessfully
#            1 failed to start
#            2 stopped sucessfully
#            3 failed to stop
#
update_gui_log() {

    [ $called_by_gui -ne 1 ] && return
    sleep 1
    [ "$2" -eq 0 ] && new_string="$1 $DONT_L10N_TEXT_SUCCESS"
    [ "$2" -eq 1 ] && new_string="$1 $DONT_L10N_TEXT_FAILED"
    EXIT_STATUS="$2"
    old_string="$DONT_L10N_TEXT_INITIAL $1"
    GUI_STATUS_STRING=`/usr/bin/echo  "$GUI_STATUS_STRING" | /usr/bin/sed s/"$old_string"/"$new_string"/g `
    /usr/bin/echo "$GUI_STATUS_STRING"  > "$GUILOGFILE"
}


start_database () {
   
   #if [ $do_service -eq 1 -o $do_event -eq 1 -o $do_topo -eq 1 ] ; then
   if [ "$do_database" != "0" ] ; then
   
      # Start the SunMC database
      #
      remove_old_start_sql_logs
    
      prstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcpwchk $SMCORAU 2>/dev/null`
      retcode=$?
      if [ $retcode -eq 2 ]; then
         echolog ''
         echolog 'The user $2 was not found by a getpwnam system call ,not in /etc/passwd, nis, nis+, etc...' "$SMCORAU"
         exit_SunMC_start "$GETPWNAM_ERROR"
      fi

      grstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcgrchk $SMCORAG 2>/dev/null`
      retcode=$?

      if [ $retcode = 2 ]; then
         echolog 'The group $2 was not found by a getgrnam system call ,not in /etc/group, nis, nis+, etc..' "$SMCORAG"
         exit_SunMC_start "$GETPWNAM_ERROR"
      fi


      if [ "$VERBOSE" = "ON" ]; then
         su - $SMCORAU -c $BASEDIR/sbin/db-start -v
      else
         su - $SMCORAU -c $BASEDIR/sbin/db-start
      fi

      if [ $? -ne 0 ]; then
         echolog "Failed to successfully perform Database Startup."
         exit_SunMC_start "$DATABASE_START_ERROR"
      fi

   fi

}

start_server() {
   if [ $do_server -eq 1 ] ; then
       check_security_keys "server" 
       [ $? -gt 0 ] && return 1
       if [ $interactive_flag -eq 1 ] ; then
          echolog "Interactive server session:"
          ( es-server.sh -i $ARGUMENT )
       else
          ( es-server.sh $ARGUMENT & )
       fi
   fi
}

start_all_services() {

   start_proc $do_hwds hdservice
   start_proc $do_trap trap
   start_proc $do_cfg cfgserver
   start_proc $do_event event
   start_proc $do_agent agent
   start_proc $do_topo topology
   start_proc $do_cstservice cstservice
   start_proc $do_platform platform
   start_proc $do_platform_instance $platform_instance_name
   start_proc $do_all_platform_instances "all_platform_instance"
   
   # Delay metadata startup to ensure there is no contention 
   if [ $do_metadata -eq 1 ]; then
      /usr/bin/sleep 30
   fi

   start_proc $do_metadata metadata
   start_proc $do_service service
   
}




start_addons() {

  [ -z "$L_ADDONS_SETUP" ] && return 0

  #This calls all available addon es-start.sh scripts placed @ BASEDIR/addons/<PROD>/sbin/
  if [ $start_addons_flag -eq 1 ] ; then

     for each_addon in `$CMD_ECHO $L_ADDONS_SETUP | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
     do 
        #echolog 'Starting addon $2...' "`get_product_names "$each_addon"`"
        addon_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "target_subdir" 2> /dev/null`
        [ $? -gt 0 ] &&  exit_SunMC "$REGISTRY_READ_ERROR"
            
        if [ -f "$BASEDIR/addons/$addon_dir/sbin/es-start.sh" ]; then
           $BASEDIR/addons/$addon_dir/sbin/es-start.sh "$addon_option"
           start_status=$?
           [ $start_status -eq 0 ] && L_ADDON_STARTED="$L_ADDON_STARTED $each_addon"
           [ $start_status -gt 0 ] && L_ADDON_FAILED="$L_ADDON_FAILED $each_addon" && EXIT_STATUS=$ADDON_START_ERROR
        else
           L_ADDON_SCRIPT_NOT_FOUND="$L_ADDON_SCRIPT_NOT_FOUND $each_addon"
        fi
     done
  fi
 
}



display_start_status() {
  
    
    if [ $do_service -eq 1 ] ; then
       /usr/bin/sleep 30 ## Need this in case of grouping services.
    else
       /usr/bin/sleep 5
    fi

    [ "$quiet_flag" = "1" ]  && return
    
    find_SunMC_proc_status

        echolog ''
        
        if [ "$do_server" = "1" ] ; then
          if [ $SunMC_server_start_error -eq 0 ] ; then
             echolog 'Java server started successfully.'    
             update_gui_log "JAVA_SERVER" 0
          else
             echolog 'Could not start Java server.'    
             update_gui_log "JAVA_SERVER" 1
          fi
        fi
        
        if [ $do_service -eq 1 -o $do_event -eq 1 -o $do_topo -eq 1 ] ; then
           if [ $database_start_error -eq 0 ] ; then
              echologverbose 'Database service started successfully.'    
           else
              echologverbose 'Could not start Database service.'    
           fi
        fi
         
        if [ "$do_service" = "1" ] ; then
          if [ $grouping_service_start_error -eq 0 ] ; then
             echolog 'Grouping service started successfully.'    
             update_gui_log "GROUPING_SERVICE" 0
          else
             echolog 'Could not start Grouping service.'    
             update_gui_log "GROUPING_SERVICE" 1
          fi
        fi
    
        if [ "$do_agent" = "1" ]; then
           checkString "$started_processes" "agent" 
           if [ $? -eq 0 ] ; then
              echolog 'Agent started successfully.'    
              update_gui_log "AGENT_PROCESS" 0
           else
              echolog 'Could not start Agent.'    
              update_gui_log "AGENT_PROCESS" 1
           fi
        fi
        
        if [ "$do_topo" = "1" ] ; then
           checkString "$started_processes" "topology" 
           if [ $? -eq 0 ] ; then
              echolog 'Topology service started successfully.'    
              update_gui_log "TOPOLOGY_SERVICE" 0
           else
              echolog 'Could not start Topology service.'    
              update_gui_log "TOPOLOGY_SERVICE" 1
           fi
        fi
        
        if [ "$do_trap" = "1" ] ; then
           checkString "$started_processes" "trap" 
           if [ $? -eq 0 ] ; then
              echolog 'Trap-handler service started successfully.'    
              update_gui_log "TRAP_SERVICE" 0
           else
              echolog 'Could not start Trap-handler service.'    
              update_gui_log "TRAP_SERVICE" 1
           fi
        fi
    
        if [ "$do_cfg" = "1" ] ; then
           checkString "$started_processes" "cfgserver" 
           if [ $? -eq 0 ] ; then
              echolog 'Configuration service started successfully.'    
              update_gui_log "CONFIGURATION_SERVICE" 0
           else
              echolog 'Could not start Configuration service.'    
              update_gui_log "CONFIGURATION_SERVICE" 1
           fi
        fi
    
        if [ "$do_event" = "1" ] ; then
           checkString "$started_processes" "event" 
           if [ $? -eq 0 ] ; then
              echolog 'Event-handler service started successfully.'    
              update_gui_log "EVENTHANDLER_SERVICE" 0
           else
              echolog 'Could not start Event-handler service.'
              update_gui_log "EVENTHANDLER_SERVICE" 1
           fi
        fi
       
        if [ "$do_cstservice" = "1" ] ; then
            checkString "$started_processes" "cstservice" 
            if [ $? -eq 0 ] ; then
               echolog 'CST service started successfully.'    
            else
               echolog 'Could not start CST service.'    
            fi
        fi
       
        if [ "$do_platform" = "1" ] ; then
           checkString "$started_processes" "platform" 
           if [ $? -eq 0 ] ; then
              echolog 'Platform agent started successfully.'    
              update_gui_log "PLATFORM_AGENT" 0
           else
              echolog 'Could not start Platform agent.'    
              update_gui_log "PLATFORM_AGENT" 1
           fi
        fi
    
        if [ "$do_metadata" = "1" ] ; then
           checkString "$started_processes" "metadata" 
           if [ $? -eq 0 ] ; then
              echolog 'Metadata Service started successfully.'    
              update_gui_log "METADATA_SERVICE" 0
           else
              echolog 'Could not start Metadata Service.'    
              update_gui_log "METADATA_SERVICE" 1
           fi
        fi
      
        if [ "$do_hwds" = "1" ] ; then

           # Find if Hardware Disagnostic Server is running
           #
           HWDS_PID_FILE="/var/opt/SUNWhwdiag/logs/hwdserver.pid"
           if [ -r "$HWDS_PID_FILE" ] ; then
              old_server_pid=`/usr/bin/cat  "$HWDS_PID_FILE"  2>/dev/null `
              old_server_pid=`/usr/bin/echo $old_server_pid 2>/dev/null `
              /usr/bin/ps -p "$old_server_pid" 1>/dev/null 2>&1
              HWDS_server_start_error=$?
           else
              HWDS_server_start_error=1
           fi

           if [ HWDS_server_start_error -eq 0 ] ; then
              echolog 'Hardware service started successfully.'    
              update_gui_log "HARDWARE_SERVICE" 0
           else
              echolog 'Could not start Hardware service.'    
              update_gui_log "HARDWARE_SERVICE" 1
           fi
        fi
    
    
        if [ "$do_platform_instance" = "1" ] ; then
           checkString "$running_instances" "$platform_instance_name" 
           if [ $? -eq 0 ]; then
               echolog '$2 - Platform instance started successfully.' "$platform_instance_name"
               update_gui_log "Platform instance $platform_instance_name" 0
           else
               echolog 'Could not start platform instance - $2.' "$platform_instance_name"
               update_gui_log "Platform instance $platform_instance_name" 1
           fi
        fi
        
        if [ "$do_all_platform_instances" = "1" ] ; then
           list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/ /,/g"`
           running_instances=`/usr/bin/echo $running_instances | /usr/bin/sed -e "s/ /,/g"`
           not_running_instances=`/usr/bin/echo $not_running_instances | /usr/bin/sed -e "s/ /,/g"`
           old_string="@ - $DONT_L10N_TEXT_INITIAL PLATFORM_INSTANCE $list_of_instances"
           GUI_STATUS_STRING=`/usr/bin/echo  "$GUI_STATUS_STRING" | /usr/bin/sed s/"$old_string"//g `
           /usr/bin/echo "$GUI_STATUS_STRING"  > "$GUILOGFILE"

           if [ ! -z "$running_instances" ] ; then
                echolog 'Following platform instances started successfully:$2$3.' "\n" "$running_instances"
                [ $called_by_gui -eq 1 ] && GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - PLATFORM_INSTANCE $running_instances $DONT_L10N_TEXT_SUCCESS`"
           fi
           
           if [ ! -z "$not_running_instances" ]; then
               echolog 'Could not start platform instance - $2.' "$not_running_instances"
               [ $called_by_gui -eq 1 ] && GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - PLATFORM_INSTANCE $not_running_instances $DONT_L10N_TEXT_FAILED`"
           fi
           /usr/bin/echo "$GUI_STATUS_STRING" > "$GUILOGFILE"

        fi 
    
        if [ "$do_web_server" = "1" ]; then
           if [ $web_server_start_error -eq 0 ] ; then
              echolog 'Web server started successfully.'
              update_gui_log "WEB_SERVER" 0
           else
              echolog 'Could not start Web server.'
              update_gui_log "WEB_SERVER" 1
           fi
        fi
    
        if [ ! -z "$L_ADDON_STARTED" ]; then
           echolog 'Following Addons started successfully:'
           echolog '$2' "`get_product_names "$L_ADDON_STARTED"`"
        fi
    
        if [ ! -z "$L_ADDON_SCRIPT_NOT_FOUND" ]; then
           echologverbose 'Start scripts for the following addons were not present:'
           echologverbose '$2' "`get_product_names "$L_ADDON_SCRIPT_NOT_FOUND"`"
        fi
    
        if [ ! -z "$L_ADDON_FAILED" ]; then
           echolog 'Following Addons failed to start:'
           echolog '$2' "`get_product_names "$L_ADDON_FAILED"`"
        fi
        
}



wait_for_topology_start() {
   
   if [ $do_topo -eq 1 ] && [ -f "${ESDIR}/delayConsole" ]; then
      [ "$quiet_flag" != "1" ] && echolog '' && echolog 'Waiting for services to come up...'
      i=1
      while [ $i -le 10 ]
      do
         /usr/bin/echo "\c."
         /usr/bin/sleep 15
         i=`expr $i + 1`
     done
     /usr/bin/rm -rf ${ESDIR}/delayConsole
   fi

}

start_console() {
   if [ $do_console -eq 1 ]; then
      if [ $num_comp -gt 0 ]; then
         es-console.sh $ARGUMENT &
      else
         es-console.sh $ARGUMENT 
      fi
   fi
}


#TODO:use this from db_start
remove_old_start_sql_logs() {
   
    /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start.log

    /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start-sql.log

    /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start-sh.log

    /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-start-vinst.log

}

exit_SunMC_start() {

  # Exit with proper exit status - $1
  #
  #echolog ''
  #if [ $1 -eq 0 ]; then
  #   echolog 'All avialable services/components started successfully."\n" '
  #else
  #   echolog 'es-start could not finish requested task."\n" '
  #fi 
  exit $1

}

################################################
# FUNCTIONS USED BY es-stop
################################################

# Prints usage for es-stop
# Input:None
# Returns:None 
#

print_usage_stop() {
    /usr/bin/echo ""
    eval /usr/bin/echo "\"`/usr/bin/gettext 'Usage : $PROGNAME -ahlYAS [-y instanceName]'`\""
    /usr/bin/gettext "     a : stops Sun Management Center Agent.\n"
    /usr/bin/gettext "     h : prints this usage report.\n"
    /usr/bin/gettext "     l : stops Platform Agent.\n"
    /usr/bin/gettext "     y : stops instance of platform agent.\n"
    /usr/bin/gettext "     Y : stops all instances of platform agents.\n"
    /usr/bin/gettext "     A : stops all Sun Management Center components except the console.\n"
    /usr/bin/gettext "     S : stops Sun Management Center Server and all the server subcomponents.\n"
    /usr/bin/echo ""
}

# Resets/Presets all flags to default values
# Input:None
# Returns:None
#
reset_flags_stop() {

   interactive_flag=0
   quiet_flag=0
   multi_flag=0
   do_console=0
   do_server=0
   do_trap=0
   do_agent=0
   do_service=0
   do_topo=0
   do_cfg=0
   do_event=0
   do_metadata=0
   do_cstservice=0
   do_platform_instance=0
   do_all_platform_instances=0
   num_comp=0
   do_platform=0
   do_hwds=0
   continue_flag=0
   do_web_server=0
   do_database=0

   server_setup=0
   agent_setup=0
   console_setup=0
   
   service_setup=0
   start_addons_flag=0
   EXIT_STATUS=0
}

update_gui_server_status() {
    GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ ${DONT_L10N_SERVERCOMP}`"
 
    if [ $SunMC_server_start_error -eq 0 ]; then
         GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL JAVA_SERVER`"
    else
         GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - JAVA_SERVER $DONT_L10N_TEXT_NOTRUNNING`"
    fi
  
    if [ $grouping_service_start_error -eq 0 ]; then
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL GROUPING_SERVICE`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - GROUPING_SERVICE $DONT_L10N_TEXT_NOTRUNNING`"
    fi
 
    checkString "$started_processes" "topology" 
    if [ $? -eq 0 ]; then
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL TOPOLOGY_SERVICE`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - TOPOLOGY_SERVICE $DONT_L10N_TEXT_NOTRUNNING`"
    fi
    
    checkString "$started_processes" "trap" 
    if [ $? -eq 0 ] ;then
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL TRAP_SERVICE`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - TRAP_SERVICE $DONT_L10N_TEXT_NOTRUNNING`"
    fi

    checkString "$started_processes" "cfgserver" 
    if [ $? -eq 0 ]; then 
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL CONFIGURATION_SERVICE`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - CONFIGURATION_SERVICE $DONT_L10N_TEXT_NOTRUNNING`"
    fi

    checkString "$started_processes" "event" 
    if [ $? -eq 0 ];then 
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL EVENTHANDLER_SERVICE`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - EVENTHANDLER_SERVICE $DONT_L10N_TEXT_NOTRUNNING`"
    fi
 
    checkString "$started_processes" "metadata" 
    if [ $? -eq 0 ]; then
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL METADATA_SERVICE`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - METADATA_SERVICE $DONT_L10N_TEXT_NOTRUNNING`"
    fi
  
    /usr/bin/ps -ef | grep -v "grep" | grep "DHWDS"   > /dev/null 2>&1
    if [ $? -eq 0 ]; then 
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL HARDWARE_SERVICE`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - HARDWARE_SERVICE $DONT_L10N_TEXT_NOTRUNNING`"
    fi

    if [ $web_server_start_error -eq 0 ] ; then
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL WEB_SERVER`"
    else
       GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - WEB_SERVER $DONT_L10N_TEXT_NOTRUNNING`"
    fi

    /usr/bin/echo "$GUI_STATUS_STRING" > "$GUILOGFILE"
}



# Stops all platform instances
# Input:None
# Returns:None
#
stop_all_platform_instances () {

    if [ ! -f "${VARDIR}/platform-instances.dat" ] ; then
        return 0
    fi
    echologverbose "Stopping all platform instances"
    list_of_instances=""
    list_of_instances=`$XGET ${VARDIR}/platform-instances.dat ControlBlock.instances`
    echologverbose 'Instances are $2' "$list_of_instances"
    if [ -z "$list_of_instances" ] ; then
        return 0
    fi

    list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/,/ /g"`

    for each_instance in $list_of_instances
    do
	es-stop.sh $each_instance 
    done
}

# Stops web server
# Kills running processes
# Input:None
# Returns:None
#
stop_web_server () {
  
    WEBSERVER_PID_FILE="$ESDIR/pid/webserver.pid"
    if [ -r "$WEBSERVER_PID_FILE" ] ; then
       old_server_pid=`/usr/bin/cat  "$WEBSERVER_PID_FILE"  2>/dev/null `
       old_server_pid=`/usr/bin/echo $old_server_pid 2>/dev/null `
       /usr/bin/ps -ep "$old_server_pid" | grep -w "$old_server_pid"  1>/dev/null 2>&1
       web_server_start_error=$?
    else
       web_server_start_error=1
    fi

    if [ "$web_server_start_error" = "1" ]; then
       echolog 'webserver is not running'
       /usr/bin/rm -f "$WEBSERVER_PID_FILE"
    else
       check_webserver
       if [ $? -ne 0 ] ; then
           if [ "$option" = "w" ]; then
               echolog 'Sun Management Center Web Server is not Installed, Can not stop web server.'
               echolog 'You must kill the process manually:$2' "$old_server_pid"
               echolog ''
           fi
           return 0
       else
           CATALINA_BASE="$BASEDIR/web/"
           export CATALINA_BASE

           CATALINA_CLASSPATH="${CATALINA_HOME}/bin/bootstrap.jar"
           [ -f "$JAVA_HOME/lib/tools.jar" ]  && CATALINA_CLASSPATH=${CATALINA_CLASSPATH}:"${JAVA_HOME}/lib/tools.jar"
           [ -f "$JAVA_HOME/jre/lib/jsse.jar" ] && CATALINA_CLASSPATH=${CATALINA_CLASSPATH}:"${JAVA_HOME}/jre/lib/jsse.jar"
         
           echolog 'Stopping webserver'  
          
           /usr/bin/echo "Stopping service Tomcat-Standalone" >> $CATALINA_BASE/logs/catalina.out # Not localized !!!
           # This will attempt to stop if JAVA_HOME is defined - if not then next kill statement will take care 

          WEBSERVER_CMD="$TMP_DIR/web_server_command.sh"

          /usr/bin/rm -f $WEBSERVER_CMD
          /usr/bin/echo "#!/bin/sh" > ${WEBSERVER_CMD}


          /usr/bin/echo "${JAVA_HOME}/bin/java -classpath ${CATALINA_CLASSPATH} \\" >> ${WEBSERVER_CMD}
          /usr/bin/echo "   -Dcatalina.base=${CATALINA_BASE} -Dcatalina.home=${CATALINA_HOME} \\" >> ${WEBSERVER_CMD}
          /usr/bin/echo "   org.apache.catalina.startup.Bootstrap stop  >/dev/null 2>&1 \\" >> ${WEBSERVER_CMD}
     
          /usr/bin/chmod 4544 ${WEBSERVER_CMD}
          /usr/bin/chown nobody ${WEBSERVER_CMD}
          ${WEBSERVER_CMD} >/dev/null 2>&1
          /usr/bin/rm -f ${WEBSERVER_CMD}
          /usr/bin/kill -9 "$old_server_pid" >/dev/null 2>&1
          return 0

       fi 
    fi
    
}

# Stops Hardware services both Agent & Server
# Input:None
# Returns:None
#
stop_hwds_service() {
    EDS_A=""
    EDS_A1=""
    EDS_A=`/usr/bin/ps -ef | /usr/bin/fgrep edagent | /usr/bin/fgrep -v fgrep | /usr/bin/awk '{ print $2 }'`

    # Stop the HWDS Agent
    /usr/bin/pkginfo -qi SUNWedag
    if [ $? -eq 0 -a ! -z "$EDS_A" ]; then
        HWDiag_dir=`/usr/bin/pkginfo -r SUNWedag`/SUNWsymon/addons/AdvancedMonitoring
        if [ 1 -lt $EDS_A ]; then
            if [ -x "$HWDiag_dir/lib/agent/ed_cmd" ]; then
                $HWDiag_dir/lib/agent/ed_cmd stop > /dev/null
                /usr/bin/sleep 1
                EDS_A1=`$HWDiag_dir/lib/agent/ed_cmd quit`
                if [ "$EDS_A1" != "QUIT DONE" ] ; then
                    # almost everything else may hang the script at this point.
                    /usr/bin/kill -9 $EDS_A
                fi
            fi
        fi
    fi

    # Stop The HWDS Server
    /usr/bin/pkginfo -qi SUNWed
    if [ $? -eq 0 ]; then
        HWDS_CMD=`/usr/bin/pkginfo -r SUNWed`/SUNWsymon/addons/AdvancedMonitoring/sbin/stop-diag
        if [ -x "$HWDS_CMD" ]; then    
            $HWDS_CMD
        fi
    fi

}


# Sets stop_flags according to options selected by user. A
# In case of wrong argument selection, prints usage & exits
# Input:None
# Returns:None
#
process_options_stop() {

   if [ $# -eq 0 ] ; then
      /usr/bin/echo ""
      /usr/bin/gettext "You must specify a component to be stopped."
      print_usage_stop
      exit 1
   fi
  
   called_by_gui=0
   /usr/bin/mkdir -p $TMP_DIR
   GUILOGFILE="$TMP_DIR/start-stop.log"
   find_SunMC_proc_status
   while getopts y:cgsmatpfehxwASlLYvrG OPT
   do
      case $OPT in
	s)
	    [ $no_server -eq 1 ] && component_missing Server
	    es-server-stop.sh
	    do_server=1
	    ;;
	m)
	    [ $no_metadata -eq 1 ] && component_missing Metadata
	    es-stop.sh metadata
	    do_metadata=1
	    ;;

	a)
            checkString "$started_processes" "agent" 
            if [ $? -eq 0 ] ; then
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ ${DONT_L10N_AGENTCOMP}\
                @ - $DONT_L10N_TEXT_INITIAL AGENT_PROCESS`"
            else
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ ${DONT_L10N_AGENTCOMP}\
                @ - AGENT_PROCESS $DONT_L10N_TEXT_NOTRUNNING`"
            fi
            
            /usr/bin/echo "$GUI_STATUS_STRING" | /usr/bin/sed "s/#/\\\t/g" > "$GUILOGFILE"

	    [ $no_agent -eq 1 ] && component_missing Agent
	    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
            [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
            unset_env_variables
            ESDIR="$AGENT_ESDIR"
            set_basedir
            es-stop.sh agent
            unset_env_variables
	    ESDIR="/var/opt/SUNWsymon"
            set_basedir
	    do_agent=1

            stop_addons_flag=1;
            addon_option="-$OPT"
	    ;;
   	l)
            checkString "$started_processes" "platform"
            if [ $? -eq 0 ] ; then
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL PLATFORM_AGENT`"
            else
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - PLATFORM_AGENT $DONT_L10N_TEXT_NOTRUNNING`"
            fi
            /usr/bin/echo "$GUI_STATUS_STRING" > "$GUILOGFILE"

	    [ $no_agent -eq 1 ] && component_missing Agent
	    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
            [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
            unset_env_variables
            ESDIR="$AGENT_ESDIR"
            set_basedir
	    es-stop.sh platform
            unset_env_variables
	    ESDIR="/var/opt/SUNWsymon"
            set_basedir
	    do_platform=1
	    ;;

	L | Y)
            ## "L" option is used internaly by setup
            get_running_instances_of_platform_agent
            initially_running_instances=`/usr/bin/echo $initially_running_instances | /usr/bin/sed -e "s/ /,/g"`
            initially_not_running_instances=`/usr/bin/echo $initially_not_running_instances | /usr/bin/sed -e "s/ /,/g"`
            if [ ! -z "$initially_running_instances" ] ; then
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL PLATFORM_INSTANCE $initially_running_instances`"
            fi
           
            if [ ! -z "$initially_not_running_instances" ]; then
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - PLATFORM_INSTANCE $initially_not_running_instances $DONT_L10N_TEXT_NOTRUNNING`"
            fi
            /usr/bin/echo "$GUI_STATUS_STRING"  > "$GUILOGFILE"
            
           
            ## "L" option is used internaly by setup
	    [ $no_agent -eq 1 ] && component_missing Agent
	    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
            [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
            unset_env_variables
            ESDIR="$AGENT_ESDIR"
            set_basedir
	    stop_all_platform_instances
            unset_env_variables
	    ESDIR="/var/opt/SUNWsymon"
            set_basedir
            do_all_platform_instances=1
            
	    ;;

	f)
	    [ $no_server -eq 1 ] && component_missing Server
	    es-stop.sh cfgserver
	    do_cfg=1
	    ;;
	g)
	    [ $no_service -eq 1 ] && component_missing Services
	    $BASEDIR/classes/base/service/bin/es-service-stop.sh
	    do_service=1
	    ;;
	h)
	    print_usage_stop
	    exit 0
	    ;;
	t)
	    [ $no_server -eq 1 ] && component_missing Server
	    es-stop.sh trap
	    do_trap=1
	    ;;
	p)
	    [ $no_server -eq 1 ] && component_missing Server
	    es-stop.sh topology
	    #
	    #Stop dicovery process
	    #
	    kill_all_processes "discover" "KILL"
	    do_topo=1
	    ;;
	e)
	    [ $no_server -eq 1 ] && component_missing Server
	    es-stop.sh event
	    do_event=1
	    ;;
	x)
	    [ $no_server -eq 1 ] && component_missing Server
	    es-stop.sh cstservice
	    #/usr/bin/pkginfo -qi SUNWcstv
            #[ $? -eq 0 ] && es-stop.sh cstservice
	    #/usr/bin/pkginfo -qi SUNWcstve
	    #[ $? -eq 0 ] && es-stop.sh cstservice
	    do_cstservice=1
	    ;;
	w)  stop_web_server
	    do_web_server=1
	    ;;
	r)
            stop_hwds_service
            do_hwds=1
            ;;
	    
	S | A)
	    if [ "$no_HA" = "0" -a $OPT = "A" ]; then
               echolog 'es-stop does not apply to Sun Management Center HA setup. Use the stopSunMC script to stop Sun Management Center.'
               exit_SunMC "$ARGUMENTS_ERROR"
	    fi

   	    if [ $no_server -eq 0 ] ; then

                update_gui_server_status

		do_metadata=1 && es-stop.sh metadata
		do_cfg=1 && es-stop.sh cfgserver
		do_topo=1 && es-stop.sh topology
		do_event=1 && es-stop.sh event
		
		if [ -f "$BASEDIR/classes/base/service/bin/es-service-stop.sh" ] ; then
		    $BASEDIR/classes/base/service/bin/es-service-stop.sh
		    do_service=1
		fi
		/usr/bin/pkginfo -qi SUNWcstv
		[ $? -eq 0 ] && do_cstservice=1 && es-stop.sh cstservice 
		/usr/bin/pkginfo -qi SUNWcstve
		[ $? -eq 0 ] && do_cstservice=1 && es-stop.sh cstservice 
                /usr/bin/pkginfo -qi SUNWcstu
                [ $? -eq 0 ] && do_cstservice=1 && es-stop.sh cstservice
		do_trap=1 && es-stop.sh trap
		do_server=1 && es-server-stop.sh
        	do_hwds=1 && stop_hwds_service
                
                #
                #Stop dicovery process
                #
                kill_all_processes "discover" "KILL"
                #
		# Shutdown the database engine
		#
		# In the future, we should check all the database
		# dependent components and shutdown the engine 
		# accordingly.
		#

		stop_db=1

		#
		# Stop the web server
		#
		do_web_server=1 && stop_web_server
                
	    fi
	    if [ $OPT = "A" ] ; then
		if [ $no_agent -eq 0 ] ; then
                    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
                    [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
                    unset_env_variables
                    ESDIR="$AGENT_ESDIR"
                    set_basedir
		    do_agent=1 && es-stop.sh agent
		    do_platform=1 && es-stop.sh platform
                    do_all_platform_instances=1 && stop_all_platform_instances
                    unset_env_variables
                    ESDIR="/var/opt/SUNWsymon"
                    set_basedir
		fi
	    fi
            stop_addons_flag=1;
            addon_option="-$OPT"
            
	    ;;
        v)
	    VERBOSE=ON
	    ;;
	y)
  
	    [ $no_agent -eq 1 ] && component_missing Agent
 	    platform_instance_name="$OPTARG"
            
            get_running_instances_of_platform_agent
            
            checkString "$running_instances" "$platform_instance_name" 
            if [ $? -eq 0 ];then
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - $DONT_L10N_TEXT_INITIAL PLATFORM_INSTANCE $platform_instance_name`"
            else
                GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - PLATFORM_INSTANCE $platform_instance_name $DONT_L10N_TEXT_NOTRUNNING`"
            fi
           /usr/bin/echo "$GUI_STATUS_STRING" > "$GUILOGFILE"

	    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
            [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
            unset_env_variables
            ESDIR="$AGENT_ESDIR"
            set_basedir
	    do_platform_instance=1 && es-stop.sh "$OPTARG"

            ;;

        G)
	    called_by_gui=1
            GUILOGFILE="$TMP_DIR/start-stop.log"
            /usr/bin/rm -f "$GUILOGFILE"
            /usr/bin/mkdir -p "$TMP_DIR"
            /usr/bin/touch "$GUILOGFILE"
            DONT_L10N_TEXT_INITIAL="GUI_STOPPING"
            DONT_L10N_TEXT_SUCCESS="GUI_STOP_SUCCESS"
            DONT_L10N_TEXT_FAILED="GUI_STOP_FAIL"
            DONT_L10N_TEXT_NOTRUNNING="GUI_NOT_RUNNING"
            DONT_L10N_SERVERCOMP="GUI_STARTSTOP_SERVERCOMP"
            DONT_L10N_AGENTCOMP="GUI_STARTSTOP_AGENTCOMP"
            GUI_STATUS_STRING="STATUS="
	    ;;

	\?)
	    print_usage_stop
	    exit 1
	    ;;
       esac
   done

}

set_stop_environment() {
  

   check_root 

   # SInce there is not concept
   # of relocation for stop call
   # the temporary directory functions
   # with blank parameters.

   remove_temp_directory
   create_temp_directory


   reset_flags_stop
   set_commondirs   
   set_basedir
 
   # Set Registry location
   #
   initializeRegistry
   
   get_SunMC_setup_status
   
   #if [ $no_server -eq 0 -o $no_console -eq 0 ] ; then
   #     checkJavaOK
   #     if [ $? -ne 0 ] ; then            
   #         echolog 'You must install a supported JDK before attempting to stop this component.'
   #        exit_SunMC_stop "$JAVA_ERROR"
   #    fi
   #fi 


   [ $no_server -eq 0 ] && set_db_env

   # Call set_xput if agent is setup
   #
   [ $no_agent -eq 0 ]  && set_xput


   PROGNAME="$0"; export PROGNAME
   ESROOT=$BASEDIR; export ESROOT
   IESROOT=$BASEDIR; export IESROOT

   check_root
 
   cd "$BASEDIR"
   PWD="$BASEDIR"; export PWD

   set_paths

   VERBOSE=OFF
   stop_db=0
   stop_addons_flag=0
   
   #This list will contain all components/services stopped successfully.
   #
   L_STOPPED=""

   #This list will contain all components/services which failed to stop.
   #
   L_FAILED=""

}




stop_database () {
   
       if [ $stop_db -eq 1 ] ; then

       get_lsnr_and_ora_proc_count
       [ $lcnt -gt 0 -o $scnt -gt 0 ] && echolog 'Stopping database.'

       if [ -f ${TMP_SMC_DB_LOGS}/db-stop.log ] ; then
          /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-stop.log
       fi

       if [ -f ${TMP_SMC_DB_LOGS}/db-stop-sql.log ] ; then
          /usr/bin/rm -rf ${TMP_SMC_DB_LOGS}/db-stop-sql.log
       fi

       prstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcpwchk $SMCORAU 2>/dev/null`
       retcode=$?
       if [ $retcode = 2 ]; then
          echolog 'The user $2 was not found by a getpwnam system call, not in /etc/passwd, nis, nis+, etc..' "$SMCORAU"
          exit_SunMC_stop "$GETPWNAM_ERROR"
       fi

       grstring=`$ESROOT/base/bin/sparc-sun-solaris${OSVERS}/smcgrchk $SMCORAG 2>/dev/null`
       retcode=$?
       if [ $retcode = 2 ]; then
          echolog 'The group $2 was not found by a getgrnam system call, not in /etc/group, nis, nis+, etc..' "$SMCORAG"
          exit_SunMC_stop "$GETPWNAM_ERROR"
       fi

       if [ "$VERBOSE" = "ON" ] ; then
          su - $SMCORAU -c $BASEDIR/sbin/db-stop -v
       else
          su - $SMCORAU -c $BASEDIR/sbin/db-stop
       fi
       get_lsnr_and_ora_proc_count
       if [ $lcnt -gt 0 -o $scnt -gt 0 ]; then
           # forcefully kill Sun Management Center database processes
           echolog ''
           echolog "Need to forcefully kill the database processes, please wait..."
           kill_ora_processes
           # "$SMCORAU" and "$SMCORAG" may not be found in the password file
           # However the semaphores and shared memory may still be allocated under this user name.
           # Will still try to remove the shared memory, if users are not available release_shm_sems
           # will not do anything.
           release_shm_sems "$SMCORAU" "$SMCORAG"
       fi

       fi
}



stop_addons () {

   [ -z "$L_ADDONS_SETUP" ] && return 0

   if [ $stop_addons_flag -eq 1 ] ; then
      
      for each_addon in `$CMD_ECHO $L_ADDONS_SETUP | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
      do
         #echolog 'Stopping $2...' "`get_product_names "$each_addon"`"
      
         addon_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "target_subdir" 2> /dev/null`
         [ $? -gt 0 ] &&  exit_SunMC "$REGISTRY_READ_ERROR"
       
         if [ -f "$BASEDIR/addons/$addon_dir/sbin/es-stop.sh" ]; then
            $BASEDIR/addons/$addon_dir/sbin/es-stop.sh "$addon_option"
            stop_status=$?
            [ $stop_status -eq 0 ] && L_STOPPED="$L_STOPPED $each_addon"
            [ $stop_status -gt 0 ] && L_FAILED="$L_FAILED $each_addon"
         fi
      done
   fi

}


display_stop_status () {

    if [ "$L_STOPPED" ]; then
       echolog 'Following Addons stopped successfully:'
       echolog '$2' "`get_product_names "$L_STOPPED"`"
    fi
   
    /usr/bin/sleep 10
    
    find_SunMC_proc_status

    echolog ''

    some_proc_running=0

    if [ "$do_server" = "1" ] ; then
       if [ $SunMC_server_start_error -eq 0 ]; then
          echolog 'Java Server is still running.' && some_proc_running=1
          update_gui_log "JAVA_SERVER" 1
       else
          update_gui_log "JAVA_SERVER" 0
       fi
    fi
    
    if [ $do_service -eq 1 -o $do_event -eq 1 -o $do_topo -eq 1 ] ; then
       [ "$do_server" = "1" ] && [ $database_start_error -eq 0 ] && echolog 'Database service is still running.' && some_proc_running=1   
    fi
     
    if [ "$do_service" = "1" ] ; then
       if [ $grouping_service_start_error -eq 0 ]; then
           echolog 'Grouping service is still running.' && some_proc_running=1   
           update_gui_log "GROUPING_SERVICE" 1
       else
           update_gui_log "GROUPING_SERVICE" 0       
       fi
    fi

    if [ "$do_agent" = "1" ]; then
       checkString "$started_processes" "agent" 
       if [ $? -eq 0 ]; then
          echolog 'Agent is still running.' && some_proc_running=1    
           update_gui_log "AGENT_PROCESS" 1
       else
           update_gui_log "AGENT_PROCESS" 0
       fi
    fi
    
    if [ "$do_topo" = "1" ] ; then
       checkString "$started_processes" "topology" 
       if [ $? -eq 0 ]; then
          echolog 'Topology service is still running.' && some_proc_running=1    
          update_gui_log "TOPOLOGY_SERVICE" 1 
       else
          update_gui_log "TOPOLOGY_SERVICE" 0 
       fi
    fi
    
    if [ "$do_trap" = "1" ] ; then
       checkString "$started_processes" "trap" 
       if [ $? -eq 0 ] ;then
          echolog 'Trap-handler service is still running.' && some_proc_running=1   
          update_gui_log "TRAP_SERVICE" 1
       else
          update_gui_log "TRAP_SERVICE" 0
       fi
    fi

    if [ "$do_cfg" = "1" ] ; then
       checkString "$started_processes" "cfgserver" 
       if [ $? -eq 0 ]; then 
          echolog 'Configuration service is still running.' && some_proc_running=1    
          update_gui_log "CONFIGURATION_SERVICE" 1
       else
          update_gui_log "CONFIGURATION_SERVICE" 0
       fi
    fi

    if [ "$do_event" = "1" ] ; then
       checkString "$started_processes" "event" 
       if [ $? -eq 0 ];then 
           echolog 'Event-handler service is still running.' && some_proc_running=1   
           update_gui_log "EVENTHANDLER_SERVICE" 1
       else
           update_gui_log "EVENTHANDLER_SERVICE" 0
       fi
    fi
   
    if [ "$do_cstservice" = "1" ] ; then
        checkString "$started_processes" "cstservice" 
        [ $? -eq 0 ] && echolog 'CST service is still running.' && some_proc_running=1   
    fi
   
    if [ "$do_platform" = "1" ] ; then
       checkString "$started_processes" "platform" 
       if [ $? -eq 0 ]; then
          echolog 'Platform agent is still running.' && some_proc_running=1   
          update_gui_log "PLATFORM_AGENT" 1
       else
          update_gui_log "PLATFORM_AGENT" 0
       fi
    fi

    if [ "$do_metadata" = "1" ] ; then
       checkString "$started_processes" "metadata" 
       if [ $? -eq 0 ]; then
          echolog 'Metadata Service is still running.' && some_proc_running=1   
          update_gui_log "METADATA_SERVICE" 1
       else
          update_gui_log "METADATA_SERVICE" 0
       fi
    fi


    if [ "$do_hwds" = "1" ] ; then
       /usr/bin/ps -ef | grep -v "grep" | grep "DHWDS"   > /dev/null 2>&1
       if [ $? -eq 0 ]; then 
           echolog 'Hardware service is still running.' && some_proc_running=1  
           update_gui_log "HARDWARE_SERVICE" 1
       else
           update_gui_log "HARDWARE_SERVICE" 0       
       fi
    fi

    if [ "$do_platform_instance" = "1" ] ; then
       checkString "$running_instances" "$platform_instance_name" 
       if [ $? -eq 0 ];then
           echolog '$2 - Platform instance is still running.' "$platform_instance_name" && some_proc_running=1
           update_gui_log "PLATFORM_INSTANCE $platform_instance_name" 1
       else
           update_gui_log "PLATFORM_INSTANCE $platform_instance_name" 0
       fi
    fi
    
    
    if [ "$do_all_platform_instances" = "1" ] ; then

       stopped_instances=""
       for each_instance in $not_running_instances
       do
          /usr/bin/echo $initially_running_instances | /usr/bin/grep $each_instance > /dev/null 2>&1
          [ $? -eq 0 ] && stopped_instances="$stopped_instances $each_instance"
       done

       list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/ /,/g"`
       running_instances=`/usr/bin/echo $running_instances | /usr/bin/sed -e "s/ /,/g"`
       not_running_instances=`/usr/bin/echo $not_running_instances | /usr/bin/sed -e "s/ /,/g"`
       not_running_instances=`/usr/bin/echo $stopped_instances | /usr/bin/sed -e "s/ /,/g"`
       old_string="@ - $DONT_L10N_TEXT_INITIAL PLATFORM_INSTANCE $initially_running_instances"
       GUI_STATUS_STRING=`/usr/bin/echo  "$GUI_STATUS_STRING" | /usr/bin/sed s/"$old_string"//g `
       /usr/bin/echo "$GUI_STATUS_STRING"  > "$GUILOGFILE"

       if [ ! -z "$running_instances" ] ; then
          echolog 'Following platform instances are still running:$2$3.' "\n" "$running_instances"
          GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - PLATFORM_INSTANCE $running_instances $DONT_L10N_TEXT_FAILED`"
          some_proc_running=1
       fi
          
       if [ ! -z "$not_running_instances" ]; then
          GUI_STATUS_STRING="$GUI_STATUS_STRING `/usr/bin/echo @ - PLATFORM_INSTANCE $stopped_instances $DONT_L10N_TEXT_SUCCESS`"
       fi

       /usr/bin/echo "$GUI_STATUS_STRING"  > "$GUILOGFILE"

    fi 

    if [ "$do_web_server" = "1" ]; then
       if [ $web_server_start_error -eq 0 ] ; then
          echolog 'Web server is still running.' && some_proc_running=1
          update_gui_log "WEB_SERVER" 1
       else
          update_gui_log "WEB_SERVER" 0  
       fi
    fi

    if [ "$L_FAILED" ]; then
       echolog ''
       echolog 'Following Addons failed to stop:$2$3' "\n" "`get_product_names "$L_FAILED"`"
    fi

    if [ "$some_proc_running" = "1" ] ; then
       echolog ''
       echolog 'Some processes may not stop immediately.'
       echolog 'Wait for five minutes before attempting to kill any process.'
    fi
   
}


exit_SunMC_stop() {

  # Exit with proper exit status - $1
  #

  #if [ $1 -eq 0 ]; then
  #   echolog 'All available services/components stopped successfully.'
  #else
  #   echolog 'es-stop could not finish requested task.'
  #fi 

  exit $1
}


