#!/bin/sh
# Copyright 03/16/05 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident  "@(#)es-common.sh	1.269 05/03/16 Sun Microsystems"


# Common commands
CMD_AWK=${COMMAND_ROOT}/usr/bin/nawk
[ -x "${COMMAND_ROOT}/usr/xpg4/bin/awk" ] && CMD_AWK=${COMMAND_ROOT}/usr/xpg4/bin/awk
CMD_BASENAME=${COMMAND_ROOT}/usr/bin/basename
CMD_CAT=${COMMAND_ROOT}/usr/bin/cat
CMD_CHMOD=${COMMAND_ROOT}/usr/bin/chmod
CMD_CHOWN=${COMMAND_ROOT}/usr/bin/chown
CMD_CLEAR=${COMMAND_ROOT}/usr/bin/clear
CMD_CP=${COMMAND_ROOT}/usr/bin/cp
CMD_CUT=${COMMAND_ROOT}/usr/bin/cut
CMD_DATE=${COMMAND_ROOT}/usr/bin/date
CMD_DF=${COMMAND_ROOT}/usr/bin/df
CMD_DIRNAME=${COMMAND_ROOT}/usr/bin/dirname
CMD_ECHO=${COMMAND_ROOT}/usr/bin/echo
CMD_EXPR=${COMMAND_ROOT}/usr/bin/expr
CMD_GREP=${COMMAND_ROOT}/usr/bin/egrep
CMD_GETTEXT=${COMMAND_ROOT}/usr/bin/gettext
CMD_HEAD=${COMMAND_ROOT}/usr/bin/head
CMD_LOCALE=${COMMAND_ROOT}/usr/bin/locale
CMD_LS=${COMMAND_ROOT}/usr/bin/ls
CMD_MKDIR=${COMMAND_ROOT}/usr/bin/mkdir
CMD_NROFF=${COMMAND_ROOT}/usr/bin/nroff
CMD_MV=${COMMAND_ROOT}/usr/bin/mv
CMD_PING=${COMMAND_ROOT}/usr/sbin/ping
CMD_PKGADD=${COMMAND_ROOT}/usr/sbin/pkgadd
CMD_PKGCHK=${COMMAND_ROOT}/usr/sbin/pkgchk
CMD_PKGINFO=${COMMAND_ROOT}/usr/bin/pkginfo
CMD_PKGPARAM=${COMMAND_ROOT}/usr/bin/pkgparam
CMD_PWD=${COMMAND_ROOT}/usr/bin/pwd
CMD_RM=${COMMAND_ROOT}/usr/bin/rm
CMD_RMDIR=${COMMAND_ROOT}/usr/bin/rmdir
CMD_SED=${COMMAND_ROOT}/usr/bin/sed
[ -x "${COMMAND_ROOT}/usr/xpg4/bin/sed" ] && CMD_SED=${COMMAND_ROOT}/usr/xpg4/bin/sed
CMD_SORT=${COMMAND_ROOT}/usr/bin/sort
CMD_SLEEP=${COMMAND_ROOT}/usr/bin/sleep
CMD_TAIL=${COMMAND_ROOT}/usr/bin/tail
CMD_TEE=${COMMAND_ROOT}/usr/bin/tee
CMD_TOUCH=${COMMAND_ROOT}/usr/bin/touch
CMD_TR=${COMMAND_ROOT}/usr/bin/tr
CMD_UNAME=${COMMAND_ROOT}/usr/bin/uname
CMD_LN=${COMMAND_ROOT}/usr/bin/ln
CMD_WC=${COMMAND_ROOT}/usr/bin/wc
CMD_TYPE=${COMMAND_ROOT}/usr/bin/type
CMD_PATCHADD=${COMMAND_ROOT}/usr/sbin/patchadd
CMD_LOCALE=${COMMAND_ROOT}/usr/bin/locale
CMD_HOSTNAME=${COMMAND_ROOT}/usr/bin/hostname
CMD_STTY=${COMMAND_ROOT}/usr/bin/stty
CMD_MORE=${COMMAND_ROOT}/usr/bin/more
CMD_READ=${COMMAND_ROOT}/usr/bin/read
CMD_INSTALLF=${COMMAND_ROOT}/usr/sbin/installf

#  Common shell functions used by various scripts
#
# Note:  This script is used internally by Sun Enterprise SyMON,
# and is not intended to be called directly by users.
# It should not be modified.
#


# new - added to check for solaris executables in setup and install right in the beginning.
#
checkSolarisExecutables() {

   #  Perform an early check to ensure that the make executable is present
   #  in the /usr/ccs/bin directory.  If not then inform user an exit.
   #
   tmp_usr_ccs_bin=/usr/ccs/bin
   tmp_make="$RELOCATED_ROOT${tmp_usr_ccs_bin}/make"
   tmp_ld="$RELOCATED_ROOT${tmp_usr_ccs_bin}/ld"
   tmp_ar="$RELOCATED_ROOT${tmp_usr_ccs_bin}/ar"

   if [ ! -f "$tmp_make" ] ; then
      echolog ""
      multiline_echolog 'The Sun Management Center server installation requires that the make executable\nbe present on the host machine. In particular it looks for this file in the\n/usr/ccs/bin directory. Install the SUNWsprot package before executing\nthe es-inst script again.'
      echolog ""
      exit_SunMC $OS_ERROR
   fi

   if [ ! -f "$tmp_ld" ] ; then
      echolog ""
      multiline_echolog 'The Sun Management Center server installation requires that the ld executable\nbe present on the host machine. In particular it looks for this file in the\n/usr/ccs/bin directory. Install the SUNWtoo package before executing\nthe es-inst script again.'
      echolog ""
      exit_SunMC $OS_ERROR
   fi

   if [ ! -f "$tmp_ar" ] ; then
      echolog ""
      multiline_echolog 'The Sun Management Center server installation requires that the ar executable\nbe present on the host machine. In particular it looks for this file in the\n/usr/ccs/bin directory. Install the SUNWbtool package before executing\nthe es-inst script again.'
      echolog ""
      exit_SunMC $OS_ERROR
   fi
   return 0
}

set_inst_base_dir() {
    /usr/bin/pkginfo -q SUNWescom
    if [ $? -eq 0 ]; then
        RELOCATIONDIR=`/usr/bin/pkgparam SUNWescom BASEDIR`        
    else
        RELOCATIONDIR="/opt"
    fi

    BASEDIR=$RELOCATIONDIR/SUNWsymon
    ESROOT="$BASEDIR"
    SYMONBASE=$RELOCATIONDIR
    export ESROOT   #  Needed by other scripts later

}

# $1 - Relocated root directory (optional)
#
set_commondirs() {
    if [ "$1" = "" ]; then
	RELOC_DIR=""
    else
	RELOC_DIR="$1"
    fi

    CONFDIR="${RELOC_DIR}/etc/opt/SUNWsymon"
    VAROPTDIR="${RELOC_DIR}/var/opt/SUNWsymon"
    export VAROPTDIR
    
    #
    # TODO for HA: check if VAROPTDIR already exists and in an invalid link.
    #
    
    PLATFORM_FILE=$VAROPTDIR/platform/platform.prop
    export PLATFORM_FILE
    VARDIR=$VAROPTDIR/cfg
    ME=`get_user_id 2> /dev/null `

    [ ! -d "$VARDIR" ] && [ "$ME" = "root" ] && $CMD_MKDIR -p "$VARDIR"

}

# this function is required to do the first time cleanup 
# Since the cleanup should happen if called from the
# CDROM keep the deletion code separate.
# this way we don't need to do removal of temp directory
# in the set_temp_directory function.


remove_temp_directory() {

    set_temp_directory

    # Handle the start related stuff before doing anything.
    # Start can be invoked by anyone so check if root then
    # try to remove or create.

    if [ -d "${TMP_DIR}" ] ; then
        ME=`get_user_id 2> /dev/null `
        if [ "$ME" = "root" ] ; then
            prev_dir=`$CMD_PWD`
            cd /
            $CMD_RM -rf "${TMP_DIR}" >> /dev/null
            ret=$?
            [ -d "$prev_dir" ] && cd $prev_dir
            if [ $ret != 0 ] ; then
                exit_SunMC
            fi
        fi
    fi
}

# Set the TMP_DIR variable and export it.
# Also create the TMP_DIR if it doesn't exist.

set_temp_directory() {

    if [ "${OSVERS}" = "" ]; then
        TMP_DIR_OS=`$CMD_UNAME -r`
    else
        TMP_DIR_OS=${OSVERS}
    fi

    if [ "${RELOCATED_ROOT}" = "" ] ; then 
        RELOC_DIR=""
    else 
        RELOC_DIR="${RELOCATED_ROOT}"
    fi

    case $TMP_DIR_OS in
        2.6*)   TMP_DIR="${RELOC_DIR}/tmp/SunMCInstall"  ;;
        5.6*)   TMP_DIR="${RELOC_DIR}/tmp/SunMCInstall"  ;;
        6)      TMP_DIR="${RELOC_DIR}/tmp/SunMCInstall"  ;;
        2.7*)   TMP_DIR="${RELOC_DIR}/tmp/SunMCInstall"  ;;
        5.7*)   TMP_DIR="${RELOC_DIR}/tmp/SunMCInstall"  ;;
        7)      TMP_DIR="${RELOC_DIR}/tmp/SunMCInstall"  ;;
        2.8*)   TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        5.8*)   TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        8)      TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        2.9*)   TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        5.9*)   TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        9)      TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        2.10*)   TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        5.10*)   TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        10)      TMP_DIR="${RELOC_DIR}/var/run/tmp/SunMCInstall"  ;;
        *)      TMP_DIR="${RELOC_DIR}/tmp/SunMCInstall" ;;
    esac
    export TMP_DIR
}


create_temp_directory() {

    set_temp_directory

    # The start related twist. Handle the same.

    if [ ! -d "${TMP_DIR}" ] ; then
        ME=`get_user_id 2> /dev/null `
        if [ "$ME" = "root" ] ; then
            $CMD_MKDIR -m 700 -p "${TMP_DIR}" >> /dev/null
            ret=$?
            if [ $ret != 0 ] ; then
                exit_SunMC
            fi
        fi

    fi

}

set_db_env() {
   /usr/bin/pkginfo -q SUNWescom
   if [ $? -eq 0 ]; then
      inst_path=`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon
   else
      inst_path="/opt/SUNWsymon"
   fi

#  ORACLE_BASE=$ESROOT/oracle; export ORACLE_BASE
   ORACLE_BASE=$inst_path/oracle; export ORACLE_BASE
   ORACLE_HOME=$ORACLE_BASE/product/8.1.7; export ORACLE_HOME
   LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH; export LD_LIBRARY_PATH
   ORA_NLS33=$ORACLE_HOME/ocommon/nls/admin/data; export ORA_NLS33
   TNS_ADMIN=$ORACLE_HOME/network/admin; export TNS_ADMIN

   # ensure that the two_task var is unset/unused for here.
   if [ -n "$TWO_TASK" ]; then
      unset TWO_TASK
   fi

   SQLPATH=$ORACLE_HOME/rdbms/admin:$BASEDIR/db/build:$BASEDIR/db/util; export SQLPATH
   ORACLE_SID=SunMC; export ORACLE_SID
   ORACLE_OWNER=root; export ORACLE_OWNER
   SUNMCLISTENER=smcdblistener; export SUNMCLISTENER
   SMCORAU=smcorau; export SMCORAU    
   SMCORAG=smcorag; export SMCORAG    
   TMP_SMC_DB_LOGS=/tmp/SunMCDBLogFiles; export TMP_SMC_DB_LOGS

   ME=`get_user_id 2> /dev/null `
   if [ "$ME" = "root" ] ; then
       if [ ! -d ${TMP_SMC_DB_LOGS} ]; then
            /usr/bin/mkdir -m 744 -p $TMP_SMC_DB_LOGS
       else
            # even if directory exists, make sure it has the right permissions
            /usr/bin/chmod 744 $TMP_SMC_DB_LOGS
       fi
       # whether this directory already exists or not, make sure it's owned by db user
       /usr/bin/chown -R $SMCORAU:$SMCORAG $TMP_SMC_DB_LOGS
   fi
   unset OPT
}

# checks the system. If the system is installed as development
# system then return 0 otherwise returns 1. If a valid SDK kay 
# is installed in the SDK license file then it is a development
# system
#
check_development_env() {

    /usr/bin/pkginfo -qi SUNWessdk > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
        return 0
    else
        return 1
    fi
}

multiline_echolog() {
    eval echo "\"`$CMD_GETTEXT "$1"`\"" 
    if [ "$LOGFILE" != "" ] ; then
	eval echo "\"`$CMD_GETTEXT "$1"`\"" >> "$LOGFILE"
    fi
}

multiline_echologverbose() {
    if [ "$VERBOSE" = "ON" ] ; then
        eval echo "\"`$CMD_GETTEXT "$1"`\"" 
    fi
    if [ "$LOGFILE" != "" ] ; then
	eval echo "\"`$CMD_GETTEXT "$1"`\"" >> "$LOGFILE"
    fi
}

echolog() {
    eval echo "`$CMD_GETTEXT "$1"`"
    if [ "$LOGFILE" != "" ] ; then
	eval echo "`$CMD_GETTEXT "$1"`" >> "$LOGFILE"
    fi
}

get_input_from_user() {
    question="$1" 
    if [ "$LOGFILE" != "" ]; then
	eval echo `$CMD_GETTEXT "$question"` " \\\c" >> "$LOGFILE"
    fi
    eval echo $GUIQSTART `$CMD_GETTEXT "$question"` $GUIQEND " \\\c" 

    read answer

    if [ "$LOGFILE" != "" ]; then
	$CMD_STTY | $CMD_GREP "\-echo" > /dev/null 2>&1 
	[ $? -ne 0 ] && $CMD_ECHO "$answer" >> "$LOGFILE"
    fi

}


ask_user() {
    question="$1"
    answer=""
    tempdomain=$TEXTDOMAIN
    while [ "$answer" = "" ]
    do
       if [ "$LOGFILE" != "" ] ; then
          eval echo `$CMD_GETTEXT "$question"` " \\\c" >> "$LOGFILE"
          eval echo `$CMD_GETTEXT '\\\(y\\\|n\\\|q\\\)'` " \\\c" >> "$LOGFILE"
       fi	
       eval echo $GUIQSTART `$CMD_GETTEXT "$question"` " \\\c" 
       setup_textdomain ES_SCRIPTS
       eval echo `$CMD_GETTEXT '\\\(y\\\|n\\\|q\\\)'` $GUIQEND " \\\c" 
       setup_textdomain $tempdomain
       read user_answer

	case "$user_answer" in
            y*) answer=1
                break
                ;;
            n*) answer=0
                break
                ;;
            q*) answer=2
                break
                ;;
            Y*) answer=1
                break
                ;;
            N*) answer=0
                break
                ;;
            Q*) answer=2
                break
                ;;
             *) echolog ''
                echo "  \c"
                setup_textdomain ES_SCRIPTS
                echolog 'Enter \\\"y\\\" or \\\"n\\\" or \\\"q\\\"'
                setup_textdomain $tempdomain
                user_answer=""
                ;;
        esac
    done

    if [ "$LOGFILE" != "" ] ; then
        echo "$user_answer" >> "$LOGFILE"
    fi

    if [ $answer -eq 2 ]; then
        echolog ''
        setup_textdomain ES_SCRIPTS
        echolog 'Exiting at user request'
        setup_textdomain $tempdomain
        exit 2
    fi
}

# Check OS version (es-common)
# $1 - supplied OSVERS (for -R option)
# 
check_osver() {
    if [ -z "$1" ]; then
        OSVERS=`${CMD_UNAME} -r`
    else
        OSVERS="$1"
    fi
    OSARCH=`${CMD_UNAME} -p`

    case $OSVERS in
        5.6*)   OSVERS=2.6  ;;
        5.7*)   OSVERS=2.7  ;;
        5.8*)   OSVERS=2.8  ;;
        5.9*)   OSVERS=2.9  ;;
        5.10*)  OSVERS=2.10
		[ ! -d "$BASEDIR/base/bin/${OSARCH}-sun-solaris${OSVERS}" ] && OSVERS=2.9;;
        *)      echolog 'Unsupported OS version: $2' "$OSVERS"
                [ -z "$OS_ERROR" ] && OS_ERROR=96
                exit_SunMC "$OS_ERROR"	    ;;
    esac
}

# Check OS version (es-inst)
# $1 - supplied OSVERS (for -R option)
# 
checkOSVersion() {
    if [ -z "$1" ]; then
	OSVERS=`${CMD_UNAME} -r`
    else
	OSVERS="$1"
    fi

    OSARCH=`${CMD_UNAME} -p`

    # OSVERSION is introduced for using in the Registry
    OSVERSION=$OSVERS
    case $OSVERS in	
	5.6*)   OSVERS=2.6  ;;
        5.7*)   OSVERS=7  ;;
	5.8*)   OSVERS=8  ;;
	5.9*)   OSVERS=9  ;;
	5.10*)   OSVERS=10  ;;
	*)      echolog 'Unsupported OS version: $2' "$OSVERS"
	        exit_SunMC "$OS_ERROR"	    ;;
    esac
}


# This function is replacement for /usr/ucb/whoami command.
# This should be used to fetch user name running script.
# Input : - None
# Returns : echos user name
#
get_user_id() {
  tmp_user_name=`/usr/bin/id | /usr/bin/cut -f2 -d'(' | /usr/bin/cut -f1 -d')' 2> /dev/null`
  tmp_user_name=`/usr/bin/echo $tmp_user_name 2> /dev/null `
  /usr/bin/echo "$tmp_user_name"
  unset tmp_user_name
}

check_root() {
    ME=`get_user_id 2> /dev/null `

    [ "$ME" = "root" ] && return 0

    $CMD_ECHO ''
    $CMD_GETTEXT "This action is limited to superuser only.\n"
    $CMD_ECHO ''
    $CMD_SLEEP 2
    exit_SunMC "$CHECK_ROOT_ERROR"

}

check_logfile() {
#
#  $1 = logfile type (install or setup)
#
    if [ -z "$LOGFILE" ] ; then
	LOGDIR=$VAROPTDIR/install
	[ ! -d "$LOGDIR" ] && $CMD_MKDIR -p "$LOGDIR"
	DATE_FORMAT=`eval echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
	TIMESTAMP=`$CMD_DATE $DATE_FORMAT`
	
	
	if [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ]; then
	    HOST=`$CMD_HOSTNAME`
            LOGFILE="$LOGDIR/$1_$HOST.$TIMESTAMP.$$"
	else
	    LOGFILE="$LOGDIR/$1_localhost.$TIMESTAMP.$$"
	fi	
    fi

    if [ ! -f "$LOGFILE" ] ; then
        $CMD_TOUCH "$LOGFILE" >/dev/null 2>&1
        $CMD_CHMOD 644 "$LOGFILE"
        if [ $? -ne 0 ] ; then
            echo ""
            eval echo `$CMD_GETTEXT 'Unable to create logfile $LOGFILE.'`
            echo ""
            [ -z "$LOGFILE_ERROR" ] && LOGFILE_ERROR=12
            exit_SunMC "$LOGFILE_ERROR"
        fi
    fi
    
    export LOGFILE

    eval echo `$CMD_GETTEXT 'Started $0 at'` '`$CMD_DATE`'. >> "$LOGFILE"
    eval echo `$CMD_GETTEXT "Running on"` `$CMD_UNAME -a`. >> "$LOGFILE"
}



check_for_l10n() {
    L10N_REQUIRED=0
    [ -z "$LANG" ] && LANG=C
    
    if [ "$LANG" != "C" ] ; then
        
        all_installed_locales="`$CMD_LOCALE -a 2> /dev/null`"
        lang_installed=`echo $all_installed_locales << $CMD_ECHO " " | $CMD_GREP -c " $LANG "`
       
        # only check if it is a valid locale on the system
        
        if [ $lang_installed -eq 0 ] ; then
            echo "LANG=${LANG} is either not valid or not installed. Defaulting to C"
            sleep 2
            LANG=C
        fi
    fi
    
    L10N_CODE=$LANG
    LC_MESSAGES=$LANG
    LC_MES_CODE=$LANG
    
    [ "$L10N_CODE" != "en" -a "$L10N_CODE" != "C" ] && L10N_REQUIRED=1
    export LANG LC_MESSAGES L10N_CODE LC_MES_CODE
}

#  PKG_DIR is the trigger here - if it is set, then we must
#  be running the install.  In that case we use /tmp/SyMON for
#  location of the link and the package dir as the TEXTDOMAIN.
#  Otherwise, everything goes in /var/opt/SUNWsymon.
#
setup_textdomain () {   

    [ "$L10N_REQUIRED" -eq 0 ] && return

    if [ $1 ]; then
        TEXTDOMAIN=$1
    else
        TEXTDOMAIN=ES_SCRIPTS
    fi
    export TEXTDOMAIN

    if [ -n "$LOCALE_DIRECTORY" -a -d "$LOCALE_DIRECTORY" ]; then
        #It is core SunMC installation
        TEXTDOMAINDIR="$LOCALE_DIRECTORY"
    else
        #
        #either Addon only installation or some other script like es-setup
        #First look into /opt area and then /var/opt area. Here we will
        # not use BASEDIR variable because this method could be called
        # by partners too.
        #

        /usr/bin/pkginfo -qi SUNWescom > /dev/null 2>&1
      if [ $? -eq 0 ] ; then
        optdir="`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon"
        if [ -f "${optdir}/lib/locale/${LANG}/LC_MESSAGES/${TEXTDOMAIN}.mo" ] ; then
            TEXTDOMAINDIR="$optdir/lib/locale/"
        else
	    TEXTDOMAINDIR=$VAROPTDIR/locale
        fi
      else
            TEXTDOMAINDIR="$SCRIPT_DIR/../image/PE/CommonForSolaris/locale"
      fi
    fi
    export TEXTDOMAINDIR

}  # setup_textdomain


# Input: $1 => exit_flag <OPTIONAL>
# If no SunMC package found, exits provided $1 != 0
#
set_basedir() {

    /usr/bin/pkginfo -qc symon
    if [ $? -eq 1 ] ; then
	echolog "No Sun Management Center Packages are installed. Exiting."
	exit 1
    fi
    
    /usr/bin/pkginfo -q SUNWescom
    if [ $? -eq 1 ];then
        echolog 'Bad installation of Sun Management Center.'
        echolog 'Clean-up the system manually and re-install Sun Management Center.'
        [ $# -gt 0 ] && [ $1 -eq 0 ] && return 1
        exit_SunMC "$BAD_INSTALLATION_ERROR"
    else 
        /usr/bin/pkginfo -qi SUNWescom
        [ $? -eq 1 ] && echolog 'Warning:Base package SUNWescom is not installed correctly.'
    fi

    BASEDIR=`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon
    CONFDIR=/etc/opt/SUNWsymon
    SYMONHOME=$BASEDIR
    export SYMONHOME
    [ -z "$ESDIR" ] && ESDIR=/var/opt/SUNWsymon
    export ESDIR
    VAROPTDIR=$ESDIR
    VARDIR=$VAROPTDIR/cfg
    PLATFORM_FILE="$VAROPTDIR/platform/platform.prop"
    export PLATFORM_FILE
 
    check_for_l10n
    [ "$L10N_REQUIRED" -eq 1 ] && setup_textdomain 

    ESROOT="$BASEDIR"
    export ESROOT   #  Needed by other scripts later

    #  This might be called by a non-root user (such as someone
    #  starting the console with es-start -c).  Only create VARDIR
    #  if running as root.
    #
    ME=`get_user_id 2> /dev/null `

    [ ! -d "$VARDIR" ] && [ "$ME" = "root" ] && /usr/bin/mkdir -p "$VARDIR" 
    
    ESPRIVATEID=esmaster; export ESPRIVATEID
    ESPUBLICID=espublic; export ESPUBLICID
    [ -z "$IESROOT" ] && IESROOT=$BASEDIR  
    export IESROOT


}

create_s10_links ()
{
    # Create any missing links for S10
    BASEDIR=`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon

    if [ `${CMD_UNAME} -r` = "5.10" ]; then
	osarch=`${CMD_UNAME} -p`
	installfDone=0
	if [ -d "$BASEDIR/base/bin/${osarch}-sun-solaris2.9" -a ! -d "$BASEDIR/base/bin/${osarch}-sun-solaris2.10" ]; then
	    ${CMD_INSTALLF} SUNWescom $BASEDIR/base/bin/${osarch}-sun-solaris2.10=./${osarch}-sun-solaris2.9 s
	    installfDone=1
	fi
	if [ -d "$BASEDIR/base/lib/${osarch}-sun-solaris2.9" -a ! -d "$BASEDIR/base/lib/${osarch}-sun-solaris2.10" ]; then
	    ${CMD_INSTALLF} SUNWescom $BASEDIR/base/lib/${osarch}-sun-solaris2.10=./${osarch}-sun-solaris2.9 s
	    installfDone=1
	fi
	if [ -d "$BASEDIR/base/sbin/${osarch}-sun-solaris2.9" -a ! -d "$BASEDIR/base/sbin/${osarch}-sun-solaris2.10" ]; then
	    ${CMD_INSTALLF} SUNWesaem $BASEDIR/base/sbin/${osarch}-sun-solaris2.10=./${osarch}-sun-solaris2.9 s
	    ${CMD_INSTALLF} -f SUNWesaem
	fi
	if [ -d "$BASEDIR/util/bin/${osarch}-sun-solaris2.9" -a ! -d "$BASEDIR/util/bin/${osarch}-sun-solaris2.10" ]; then
	    ${CMD_INSTALLF} SUNWescom $BASEDIR/util/bin/${osarch}-sun-solaris2.10=./${osarch}-sun-solaris2.9 s
	    installfDone=1
	fi
	[ $installfDone -eq 1 ] && ${CMD_INSTALLF} -f SUNWescom
    fi
}

# This function added for HA 
# Input: $1 = new ESDIR
#
change_esdir() {
   ESDIR="$1"
   [ -z "$ESDIR" ] && ESDIR=/var/opt/SUNWsymon
   set_basedir
}    
  
set_xput() {

    [ -z "$OSVERS" ] && check_osver
#    XPUT="$BASEDIR/base/sbin/${ARCH}-sun-solaris${OSVERS}/xput"
    XPUT="$BASEDIR/base/sbin/xput"
    if [ ! -x "$XPUT" ] ; then
        echolog ""
        echolog 'Could not find xput executable: $2' $XPUT
        echolog ""
        exit 1
    fi
    XGET=`echo "$XPUT" | /usr/bin/sed s/xput/xget/`
}

# Find installation status from Registry
#
set_inst_flags() {

   no_agent=1
   no_server=1
   no_console=1
   no_service=1
   no_metadata=1
   no_HA=1
   no_DE=1
   
   /usr/bin/pkginfo -qi SUNWescli
   no_cli=$?
   
   
   BASE_PRODUCT="PRODUCT.PE"

   base_inst_status=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$BASE_PRODUCT" "install-status" 2> /dev/null `
   [ "$base_inst_status" != "1" ] && return 1

   L_BASE_INSTALLED_LAYERS=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer" "key"  2> /dev/null `
   [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
   L_BASE_INSTALLED_LAYERS=`$CMD_ECHO $L_BASE_INSTALLED_LAYERS | /usr/bin/sed "s/,/ /g"`
   
   temp_str=`/usr/bin/echo $L_BASE_INSTALLED_LAYERS | /usr/bin/grep -w SERVER`
   [ "$temp_str" ] && no_server=0 && no_metadata=0 && no_service=0
    
   temp_str=`/usr/bin/echo $L_BASE_INSTALLED_LAYERS | /usr/bin/grep -w AGENT `
   [ "$temp_str" ] && no_agent=0
    
   temp_str=`/usr/bin/echo $L_BASE_INSTALLED_LAYERS | /usr/bin/grep -w CONSOLE `
   [ "$temp_str" ] && no_console=0
    
   BASE_COMPONENTS=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$BASE_PRODUCT" "component" "key"  2> /dev/null `
   temp_str=`/usr/bin/echo $BASE_COMPONENTS | /usr/bin/grep -w COMPONENT.HA 2> /dev/null `
   [ "$temp_str" ] && no_HA=0

   BASE_COMPONENTS=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$BASE_PRODUCT" "component" "key"  2> /dev/null `
   temp_str=`/usr/bin/echo $BASE_COMPONENTS | /usr/bin/grep -w COMPONENT.SDK 2> /dev/null `
   [ "$temp_str" ] && no_DE=0

   return 0
}


set_paths() {

    
    if [ ! -f $BASEDIR/startup.profile ] ; then
	echolog 'Cannot find file $2' "$BASEDIR/startup.profile"
	exit 1
    fi
    
    User_Env_Path=`echo $PATH`

    . "$BASEDIR"/startup.profile
    
    PATH=$PATH:/usr/ccs/bin:$User_Env_Path
    export PATH
 
    ESROOT="$BASEDIR"

    if [ ! -f "$BASEDIR"/es.profile ] ; then
	echolog 'Cannot find file $2' "$BASEDIR/es.profile"
	exit 1
    fi

    #   The following if condition is here for the reason that
    #   the console installations do not have the base-setup.sh
    #   It is okay not to source this file in case of console.
    #
    if [ -f "$BASEDIR"/base/sbin/base-setup.sh ] ; then
	[ -n "$ESENV" ] && unset ESENV
	. "$BASEDIR"/es.profile
    fi

}

unset_env_variables() {

    #[ -n "$JAVA_HOME" ] && unset JAVA_HOME

    #  If we are running the Korn shell AND ENV is set then unset it.
    #  This prevents executing the ENV file, which runs when
    #  jre is executed.  It is common to put a setting for JAVA_HOME in that file.
    #
    #
    # Make sure SHELL is set . SHELL may not be set when Invoked from 
    # rc3.d.
    #

    if [ -n "$SHELL" ]; then
        [ `/usr/bin/expr "$SHELL" : '.*\(...\)'` = "ksh" ] && [ -n "$ENV" ] && unset ENV
    fi	

    if [ -n "$ESENV" ] ; then
        #echo "ESENV already set. Unsetting."
        unset ESENV
    fi
}

#
# $1=Dat file name
#
move_datfile() {
    if [ -f "$1" ] ; then
        echologverbose 'Moving $2 to $3' "$1" "$1.old"
        /usr/bin/mv "$1" "$1.old"
    fi
}

#  $1 = unique string used to identify process in ps output
#  $2 = signal to send to the process
#
kill_processes() {

    [ $1 -ne 0 ] && return 0

#   pids=`/usr/ucb/ps -ww -a -g -x | /usr/bin/fgrep SUNWsymon | \
#   /usr/bin/fgrep -v grep | /usr/bin/fgrep "$1" | /usr/bin/awk '{print $1}'`
    pids=`/usr/bin/ps -eaf | /usr/bin/fgrep SUNWsymon | \
    /usr/bin/fgrep -v grep | /usr/bin/fgrep "$1" | /usr/bin/awk '{print $2}'`
    for each_pid in $pids
    do
        if [ -z "$2" ] ; then
            /usr/bin/kill "$each_pid" >/dev/null 2>&1
        else
            /usr/bin/kill -s "$2" "$each_pid" >/dev/null 2>&1
        fi
    done

}

#  $1 = X object value checked
#  $2 = component
#  $3 = port
#
port_busy() {
 
   #  Save the original port number for use later
   port1="$3"
   echolog ''
   echolog '---------------------------- WARNING ---------------------------'
   echolog 'It appears that $2 $3 is already in use.' "$1" "$port"
   echolog 'Sun Management Center $2 may not be able to run due to this conflict.' "$2"
   echolog 'There are two ways to correct this conflict:'
   echolog '    1. Reconfigure the port that Sun Management Center uses.'
   echolog '    2. Stop the process that is using the port.'
   #proc_count=`/usr/bin/ps -aef | /usr/bin/fgrep -v grep | \
   #/usr/bin/grep snmpdx | /usr/bin/wc -l`
   #if [ "$proc_count" -ne 0 ] ; then
   #   echolog 'You are currently running snmpdx, which may be causing the conflict.'
   #   echolog ''
   #fi
   echolog 'Press RETURN to force default port.'
   retcode=1
   READ_RESPONSE_ONCE=0
   while [ $retcode -ne 0 ]; do

      fetch_response_text "TAG=${2}_OPTIONAL_PORT" "Enter port you would like to use [ 1100 to 65535 ]:"
     
      [ -z "$answer" ] && answer="s" && break

      [ $answer = "DEFAULT" ] && answer="s" && break

      /usr/bin/expr $answer + 1  1> /dev/null  2>&1 
      retcode=$?
      if [ $retcode -ne 0 ] ; then
         echolog 'Port $2 is not a valid port number. Try again.' "$answer"
         continue
      fi

      if [ $answer -lt 1100 -o $answer -gt 65535 ] ; then
         echolog 'Invalid port. Try again.'
         
         if [ "$flash_questions_to_console" = "0" ]; then
            answer="s"
            break
         fi 
         
         retcode=1
         continue
      fi         

      check_port_number $1 $2 $answer
      retcode=$?
      [ $retcode -eq 0 ] && break
      
      echolog 'The port you entered is busy. Try again.'

   done
   
   port="$answer"

   if [ "$port" != "s" ] ; then
      echologverbose 'Updating $2 with new port number.' "$VARDIR/domain-config.x"
      [ -x "$XPUT" ] && set_xput
      $XPUT $VARDIR/domain-config.x "$1" "$answer"
   else 
	echolog ""
#	echolog 'NOTE: Prior to starting Sun Management Center $2, stop the process using port $3.' "$2" "$port1"
        
   fi


}


#  $1 = domain-config.x parameter to check
#  $2 = process to check
#  $3 = PORT
#
check_port_number() {

    L_ALL_SUNMC_PORTS=`$XGET ${TMP_DIR}/sunmc_ports.x  ALL_SUNMC_PORTS 2> /dev/null`
    /usr/bin/echo "$L_ALL_SUNMC_PORTS" | /usr/bin/grep -w $3  > /dev/null
    [ $? -eq 0 ] && return 1 # Port already occupied by other sunmc proc

    /usr/bin/netstat -an | /usr/bin/grep "\*\.$3 " >/dev/null
    [ $? -ne 0 ] && return 0

    #  Make sure it isn't in use by one of the SyMON processes!
    #
    numproc=`/usr/bin/ps -aef | /usr/bin/grep 'esd - init $2' | \
    /usr/bin/grep -v /usr/bin/grep | /usr/bin/wc -l`
    numproc=`echo $numproc`
    [ "$numproc" -eq 0 ] && return 1
   
    return 0
}

# Checks if SMA is configured to run on port 161
# by parsing the /etc/sma/snmp/snmpd.conf file
# Relevant only on Solaris 10 and above
isSMAOn161 () {
    sma_on_161=0
    cfgfile=/etc/sma/snmp/snmpd.conf
    /bin/grep -wi agentaddress $cfgfile > /dev/null 2>&1
    if [ $? -eq 1 ]; then
	sma_on_161=1
    else 
	/bin/grep -wi agentaddress $cfgfile | /bin/grep -w 161 > /dev/null 2>&1
	[ $? -eq 0 ] && sma_on_161=1
    fi
    return $sma_on_161
}

# Inputs  $1 = domain-config.x parameter to check
#         $2 = process to check
#         
# Returns - sets newly set port in rspononse file
#
check_port() {
    port=""
    port=`$XGET "$VARDIR/domain-config.x" $1`
    oldport=$port

    check_port_number $1 $2 $port
    if [ $? -ne 0 ]; then
	port_busy $1 $2 $port
    else
	osrev=`${CMD_UNAME} -r|${CMD_CUT} -d"." -f2`
	sma_on_161=0
	# If on Solaris 10 and above and checking for port 161
	# check whether SMA is configured to run on 161
	# even if the snmpd process is not running
	if [ $port = "161" -a $osrev -gt 9 ]; then
	    isSMAOn161
	    sma_on_161=$?
	fi
	[ $sma_on_161 -eq 1 ] && port_busy $1 $2 $port
    fi
    
    [ "$port" != "s" -a "$oldport" != "$port" ] && saveAutoConfig "${2}_OPTIONAL_PORT" "$port"
 
    # If selected, add it to L_ALL_SUNMC_PORTS
    # 
    [ "$port" = "s" ] && port="$oldport"
    L_ALL_SUNMC_PORTS=`$XGET ${TMP_DIR}/sunmc_ports.x  ALL_SUNMC_PORTS 2> /dev/null`
    L_ALL_SUNMC_PORTS="$L_ALL_SUNMC_PORTS<$port>"
    $XPUT "${TMP_DIR}/sunmc_ports.x" "ALL_SUNMC_PORTS" "$L_ALL_SUNMC_PORTS"

}




#this defines few easy functions to deal with the configuration
#file. The configuration file for these functions has very simple
#format. They can have comments and comments must start with '#' at
#the first charcter position.
#Every noncomment line in the file will represent a name value pair.
#The format of the name value pair is 'name=value'
#the name must start at the first character. The name is case sensitive.


#gets the value of variable from cfgfile. If file not present
#or not writable then returns 2.If variable is not in file then 
#returns 1 else returns 0 and prints out the value on stdout

get_value_from_cfgfile()
{
    cfgfile=$1
    variable=$2
    separator=$3
    if [ ! -r $cfgfile ] ; then
        return 2
    fi
    varline=""
    varline=`/usr/bin/cat $cfgfile | /usr/bin/grep "^$variable$separator" 2> /dev/null`
    if [ -z "$varline" ] ; then
         return 1
    fi
    value=`echo $varline | /usr/bin/cut -f2 -d $separator `
    echo $value
    return 0
}

#puts the variable and value pair in the cfgfile. If file not present
#or not writable then returns 2 else returns 0. If the variable is 
#already defined in the file then replaces the old by new one.

put_var_in_cfgfile()
{
    cfgfile=$1
    variable=$2
    value=$3
    separator=$4
    if [ -z "$cfgfile" ] ; then
        return 2
    fi
    if [ ! -w "$cfgfile" ] ; then
        return 2
    fi
    varline=""
    varline=`/usr/bin/cat $cfgfile | /usr/bin/grep "^$variable$separator" 2> /dev/null`
    if [ -z "$varline" ] ; then
         echo "$variable$separator$value" >> $cfgfile
         return 0
    fi
    /usr/bin/mv $cfgfile $cfgfile.old
    while read LINE
    do
        echo $LINE | /usr/bin/grep "^$variable$separator" > /dev/null 2>&1 
        if [ $? -eq 0 ] ; then
           echo "$variable$separator$value" >> $cfgfile
              continue
        fi
        echo $LINE >> $cfgfile
     
    done  < $cfgfile.old
    return 0
    
}

# puts the variable and value pair in the cfgfile. If file not present
# or not writable then returns 2 else returns 0. If the variable is 
# already defined in the file then appends the new value in the old value.

append_var_in_cfgfile()
{
    cfgfile=$1
    variable=$2
    value=$3
    separator=$4
    if [ ! -w $cfgfile ] ; then
        return 2
    fi
    varline=""
    varline=`/usr/bin/cat $cfgfile | /usr/bin/grep "^$variable$separator" 2> /dev/null`
    if [ -z "$varline" ] ; then
         echo "$variable$separator$value" >> $cfgfile
         return 0
    fi
    /usr/bin/mv $cfgfile $cfgfile.old
    while read LINE
    do
        echo $LINE | /usr/bin/grep "^$variable$separator"  > /dev/null 2>&1
        if [ $? -eq 0 ] ; then
            currentvalue=`echo $LINE | /usr/bin/cut -f2 -d$separator`
            echo "$variable$separator$currentvalue $value" >> $cfgfile
            continue
        fi
        echo $LINE >> $cfgfile
     
    done  < $cfgfile.old
    return 0
}

# removes one entry from the file. If the file is not present or not 
# writable then returns 2 else returns 0.
#
remove_var_from_cfgfile()
{
    cfgfile=$1
    variable=$2
    separator=$3
    if [ ! -w $cfgfile ] ; then
        return 2
    fi
    varline=""
    varline=`/usr/bin/cat $cfgfile | /usr/bin/grep "^$variable$separator" 2> /dev/null`
    if [ -z "$varline" ] ; then
         return 0
    fi
    /usr/bin/mv $cfgfile $cfgfile.old
    while read LINE
    do
        echo $LINE | /usr/bin/grep "^$variable$separator"  > /dev/null 2>&1
        if [ $? -eq 0 ] ; then
           continue
        fi
        echo $LINE >> $cfgfile
     
    done  < $cfgfile.old
    return 0
}


is_port_open()
{
    /usr/bin/netstat -an | /usr/bin/grep "\*\.$1 " >/dev/null
    [ $? -ne 0 ] && return 0
    return 1
}

echologverbose() {
    if [ "$VERBOSE" = "ON" ] ; then
        eval echo "`/usr/bin/gettext "$1"`"
    fi
    if [ "$LOGFILE" != "" ] ; then
        eval echo "`/usr/bin/gettext "$1"`" >> "$LOGFILE"
    fi
}



# This function modified version of "get_security_key()" 
#
# If required, reads seed 
# Input : $1 = if 1 then forces default seed elase gives user option to select seed
# Returns : sets security_seed="$seed"
#
get_security_key () {
    
    # 3.5 Automated setup will not support SEED question. 
    # GUI will pass SEED to base setup by exporting SECURITY SEED variable.
    [ ! -z "$SECURITY_SEED" ] && security_seed="$SECURITY_SEED" && seed="$SECURITY_SEED" && return 0

    echolog ''
    multiline_echolog 'Sun Management Center requires an encrypted security key for communication\nbetween processes. The security key is generated based on a unique password\nseed you provide. The same security key is used for the server and all\nagents. You must ensure that you use the same seed for all the machines you\ninstall.'
    
    if [ "$1" = "1" ]; then
       seed=maplesyr
    else
      while [ 1 ]; do
         key_entered=0
         while [ $key_entered -eq 0 ]; do
            /usr/bin/stty -echo
            get_input_from_user  "Enter the seed to generate keys:"  
            /usr/bin/stty echo
            echolog ''
            key_entered=1
            keylength=`echo "$answer" | /usr/bin/wc -m 2> /dev/null `
            keywords=`echo "$answer" | /usr/bin/wc -w 2> /dev/null `
            #
            # 8 char is allowed wc always returns 1 more
            #
            if [ $keylength -gt 9 -o $keywords -gt 1 ] ; then
                echolog 'The password seed length must be less than 8 characters, and contain no spaces.'
                key_entered=0
                continue
            fi
            [ -z "$answer" ] && key_entered=0
         done

         temp_seed=$answer
         
         #[ ! -z "$AUTOCONFIG_RUNFILE" ] && seed=$temp_seed && break
         
         /usr/bin/stty -echo
         get_input_from_user "Re-enter the seed to confirm:"  
         /usr/bin/stty echo
         echolog ''   
         [ "$answer" = "$temp_seed" ] && seed=$temp_seed && break

         echolog 'The seed you entered second time is not same as first.'
         echolog ''
      done

    fi
    key_char_count=`/usr/bin/echo $seed | /usr/bin/wc -c`
    [ $key_char_count -gt 9 ] && seed=`/usr/bin/echo $seed  | /usr/bin/cut -c1-8`
    security_seed="$seed"
    # 3.5. Automated setup will not support security seed question.
    #saveAutoConfig "SECURITY_KEY_SEED" "$security_seed"
    echolog ''
    unset key_char_count temp_seed
    return 0
}

# Read SNMPV1 community string from user
#
#
# If required, reads seed 
# Input : $1 = if 1 then forces default community string.
# Returns : sets security_seed="$seed"
#
get_SNMPV1_community_string() {

    # 3.5 Automated setup will not support question to configure SNMP community string.
    # GUI wizard will export this variable before calling setup.
    #
    [ ! -z "$SNMPV1_STRING" ] && export SNMPV1_STRING && return 0

    echolog ''
    multiline_echolog 'An SNMPv1 community string is required for security, and by default is set\nto *public*. If you want additional security, specify a customized string.\nYou must use the same SNMPv1 community string on all of the machines on which\nyou install Sun Management Center 3.5 Update 1. Press RETURN to force default value.'

 
    if [ "$1" = "1" ]; then
       SNMPV1_STRING="public"
    else
       while [ 1 ]; do
          #echolog 'Press RETURN to force default value.'
          /usr/bin/stty -echo
          get_input_from_user "Enter SNMPv1 community string:"  
          /usr/bin/stty echo
 
          [ -z "$answer" ] && SNMPV1_STRING="public" && break

          keywords=`echo "$answer" | /usr/bin/wc -w 2> /dev/null `
          if [ $keywords -gt 1 ] ; then
             echolog ''
             echolog 'Invalid SNMPV1 community string. Blank spaces are not allowed.'  
             continue
          fi  
          
          temp_string="$answer"
          echolog ''
          /usr/bin/stty -echo
          get_input_from_user "Re-enter the SNMPv1 community string to confirm:"  
          /usr/bin/stty echo
          echolog ''   
          [ "$answer" = "$temp_string" ] && SNMPV1_STRING="$answer" && break
 
          echolog 'This does not match the string you entered first time.'
          echolog ''
       done
    fi
    
    # 3.5 will not have this tag in resp. summary file.
    #saveAutoConfig "SNMPV1_COMMUNITY_STRING" "$SNMPV1_STRING"
    echolog ''
    export SNMPV1_STRING

    return 0
}

# $1 sunmc component 
#
configure_community_string_file() {

   community_file="${ESDIR}/cfg/${1}-community.dat"
   if [ -f "$community_file" ]; then
      merged=`$XGET $community_file merged`
      if [ "$merged" = "-1" ]; then
          old_string=`$XGET $community_file new`
      else
          old_string=`$XGET $community_file old`
      fi

      /usr/bin/mv -f "$community_file" "${community_file}.old"
      /usr/bin/chmod 600 ${community_file}.old

      /usr/bin/cat "${community_file}.old" | /usr/bin/grep -v merged > "$community_file"
      [ -z "$old_string" ] && old_string="public"
      $XPUT $community_file old $old_string
      $XPUT $community_file new $SNMPV1_STRING
      /usr/bin/chmod 600 $community_file
   else
      if [ "$SNMPV1_STRING" != "public" ] ; then
          [ -z "$old_string" ] && old_string="public"
          $XPUT $community_file old $old_string
          $XPUT $community_file new $SNMPV1_STRING
          /usr/bin/chmod 600 $community_file
      fi 
   fi
}

#  $1 = unique string used to identify process in ps output
#  $2 = signal to send to the process
#
kill_all_processes() {

#     pids=`/usr/ucb/ps -ww -a -g -x | /usr/bin/fgrep -v grep | \
#     /usr/bin/fgrep "$1" | /usr/bin/awk '{print $1}'`
      pids=`/usr/bin/ps -eaf | /usr/bin/fgrep -v grep | \
              /usr/bin/fgrep "$1" | /usr/bin/awk '{print $2}'`
    for each_pid in $pids
    do
        if [ -z "$2" ] ; then
            /usr/bin/kill "$each_pid" >/dev/null 2>&1
        else
            /usr/bin/kill -s "$2" "$each_pid" >/dev/null 2>&1
        fi
    done

}

# Gets a value from a specified automated configuration file
# $1 = key
# Return: the value of the key
#
getAutoConfig() {
    if [ "$AUTOCONFIG_RUNFILE" = "" ] ; then
        echo ""
    else
        tmp_getautoconfig=`$CMD_GREP "^${1}=" "$AUTOCONFIG_RUNFILE"`
        if [ "$tmp_getautoconfig" = "" ] ; then
            echo ""
	else
            # Config file must support entries with white spaces in between 
            #
            /usr/bin/echo `$CMD_EXPR "$tmp_getautoconfig" : "${1}\(.*\)" | $CMD_CUT -d= -f2`
	fi
    fi
}

# Saves a value to a specified automated configuration file
# $1 = key
# $2 = value
#
saveAutoConfig() {
    [ "$AUTOCONFIG_SAVEFILE" = "" ] && return
    /usr/bin/grep "${1}=" $AUTOCONFIG_SAVEFILE > /dev/null 2>&1 # -w option can not be used here 
    [ $? -eq 0 ] && return # should not add duplicate key if present. Preseve old value
    echo "${1}=${2}" >> "$AUTOCONFIG_SAVEFILE"
}

# Exit SunMC
# Input : $1 => EXIT_STATUS_CODE
exit_SunMC () {

  /usr/bin/echo $PROGNAME | grep "s31" > /dev/null 2>&1 
  [ $? -eq 0 ]  && exit_SunMC_setup $1

  /usr/bin/echo $PROGNAME | grep "setup" > /dev/null 2>&1 
  [ $? -eq 0 ]  && exit_SunMC_setup $1
  
  /usr/bin/echo $PROGNAME | grep "es-inst" > /dev/null 2>&1 
  [ $? -eq 0 ]  && exit_SunMC_install $1


  /usr/bin/echo $PROGNAME | grep "es-uninst" > /dev/null 2>&1 
  [ $? -eq 0 ]  && exit_SunMC_uninstall $1

  /usr/bin/echo $PROGNAME | grep "start" > /dev/null 2>&1 
  [ $? -eq 0 ]  && exit_SunMC_start $1

  /usr/bin/echo $PROGNAME | grep "stop" > /dev/null 2>&1 
  [ $? -eq 0 ]  && exit_SunMC_stop $1

  echolog 'Exiting...'
  exit $1
  
}

#reads $JAVA and sets $JAVA to actual pathname
getJavaHomeFromPath() {
        $CMD_TYPE java > /dev/null
        if [ $? -ne 0 ] ; then
            echolog 'Sun Management Center requires complete installation of $2 or above.' "$JAVA_MINIMUM_REQUIRED"
            echolog 'Set the JAVA_HOME variable to point to a supported JDK version and export it.'
            return 1
        fi               
        JAVA=`$CMD_TYPE java | cut -d' ' -f3` 
}

# Checks for external components used by SunMC - WebServer and Java
#


# Check presence of Apache Tomcat server
# This function can be used to check presence
# and locate location of webserver
# This function shall be called once the get_SunMC_setup status i
#
check_webserver () {
    
    # Check Presence of tomcat packages
    #    
    /usr/bin/pkginfo -qi SUNWtcatu 
    if [ $? -eq 0 ]; then
       CATALINA_HOME=`/usr/bin/pkginfo -r SUNWtcatu  2>/dev/null  `
       CATALINA_HOME="$CATALINA_HOME/usr/apache/tomcat"
       export CATALINA_HOME
       return 0
    fi # Else nothing required.
    return 1
}


# Java version checking
# This function expects JAVA_HOME to be pointing to the base of the 
# directory containing a full JDK.
#
#
# Return: 0 - valid java found
#         1 - java not found
#         2 - JAVA found but not JAR
# Sets: SYMON_JAVAHOME JAVA_VERSION and JAVA_FULLVERSION
# Requires: FOR_WIZARD flag, for GUI preliminary check.

checkJavaOK() {   
    JAVA_CHECK=1
    JAVA_CFG_FILE="${VAROPTDIR}/cfg/java.home"
    
    if [ "$FOR_WIZARD" = "1" ] ; then    
        JAVA_MINIMUM_REQUIRED="Solaris JDK 1.2.2"
    else
        JAVA_MINIMUM_REQUIRED="Solaris JDK 1.3.1"
        
        SERVER_INSTALL=0    
        $CMD_PKGINFO $RELOC_PARAM -qi SUNWessrv
        if [ $? -eq 0 ] ; then
            SERVER_INSTALL=1
        else
            checkString "$INSTALL_LAYERS" "LAYER.SERVER"
            [ $? -eq 0 ] && SERVER_INSTALL=1
        fi 

        if [ $SERVER_INSTALL -eq 1 ] ; then
            JAVA_MINIMUM_REQUIRED="Solaris JDK 1.4.2"     
        fi
    fi
    
    if [ -n "$JAVA_HOME" ] ; then        
        checkJavaValid
        JAVA_CHECK=$?
        [ $JAVA_CHECK -eq 0 ] && return $JAVA_CHECK        
    fi
    if [ -f "$JAVA_CFG_FILE" ] ; then        
        JAVA_HOME=`get_value_from_cfgfile "$JAVA_CFG_FILE" "JAVA_HOME" "="`
        if [ -n "$JAVA_HOME" ] ; then
            checkJavaValid
            JAVA_CHECK=$?
            [ $JAVA_CHECK -eq 0 ] && return $JAVA_CHECK
        fi        
    fi    
    if [ -f "/usr/j2se/bin/java" ] ; then
        JAVA_HOME=/usr/j2se
        checkJavaValid
        JAVA_CHECK=$?
        [ $JAVA_CHECK -eq 0 ] && return $JAVA_CHECK
    fi
    if [ -f "/usr/java/bin/java" ] ; then
        JAVA_HOME=/usr/java
        checkJavaValid
        JAVA_CHECK=$?
        [ $JAVA_CHECK -eq 0 ] && return $JAVA_CHECK
    fi  
    
    [ -z "$SYMON_JAVAHOME" ] && echolog 'Required java version could not be found!!'
    
    echolog ''
    
    multiline_echolog 'You can either\n\n1) Set the environment variable JAVA_HOME.\n\t\tOR\n2) Edit the $2 file to point to\na valid JDK installation.' "$JAVA_CFG_FILE"
    echolog ''
    echolog 'Otherwise, java is searched for at /usr/j2se and finally at /usr/java.'        
    echolog ''
    echolog 'For the components selected, you need $2 or above.' "$JAVA_MINIMUM_REQUIRED" 
    
    return $JAVA_CHECK

}   

# requires JAVA_HOME and JAVA_MINIMUM_REQUIRED and FOR_WIZARD flag, if required.
#
checkJavaValid() {

    JAVA=${JAVA_HOME}/bin/java
    JAR=${JAVA_HOME}/bin/jar
    JAVA_VERSION=""
    JAVA_FULLVERSION=""
    retval=0

    if [ ! -x "$JAVA" ] ; then
        retval=1
    else
        JAVA_VERSION=`$JAVA -version 2>&1 | $CMD_HEAD -1 | $CMD_CUT -d' ' -f3`
        JAVA_FULLVERSION=`$JAVA -fullversion 2>&1 | $CMD_HEAD -1 | $CMD_CUT -d' ' -f4`
    fi

    [ ! -x "$JAR" ] && retval=2
    
    if [ $retval -eq 0 ] ; then
        MINOR=""    
        OUT=`$CMD_ECHO $JAVA_VERSION  | $CMD_TR -d "\"" | $CMD_TR '.' ' '`
        set $OUT   
    
        case $1 in   
        1*)  case $2 in
                0*)  retval=1
                     ;;
                1*)  retval=1
                     ;;                           
                2*)  if [ "$FOR_WIZARD" = "1" ] ; then
                         case $3 in
                             0*) retval=1
                                 ;;
                              *) retval=0
                                 ;;
                         esac                       
                     else
                         retval=1 
                     fi            
                     ;;
                3*)  if [ "$FOR_WIZARD" = "1" ] ; then
                         retval=0
                     else
                         retval=1
                         if [ "$JAVA_MINIMUM_REQUIRED" = "Solaris JDK 1.3.1" ] ; then
                             case $3 in
                                 0*) retval=1
                                     ;;
                                  *) retval=0
                                     ;;
                             esac
                         fi 
                     fi       
                     ;;  
                 4*) if [ "$FOR_WIZARD" = "1" ] ; then
                              retval=0
                     else
                         retval=1
                              if [ "$JAVA_MINIMUM_REQUIRED" = "Solaris JDK 1.4.2" ] ; then
                             case $3 in  # The micro release needs to be 2 now for lockhart.
                                 0*) retval=1 # if 1.4.0 then not correct.
                                     ;;
                                 1*) retval=1 # if 1.4.1 then also not correct
                                     ;;
                                 *) retval=0 # if 1.4.2 or above then OK.
                                     ;;
                             esac
                         else
                             retval=0
                              fi
                          fi
                          ;;
                 *)  retval=0
                     ;;
            esac
            ;;               
        
        *)    retval=1
            ;;
        esac
    fi
    
    if [ $retval -eq 0 ] ; then     
        SYMON_JAVAHOME=$JAVA_HOME
        echologverbose 'SYMON_JAVAHOME is set to: $2' "$SYMON_JAVAHOME"        
        echologverbose 'JDK version is: $2' "$JAVA_FULLVERSION"
        export JAVA JAVA_VERSION JAVA_FULLVERSION SYMON_JAVAHOME JAVA_HOME
    elif [ $retval -eq 2 ] ; then
        # java, no jar
        #
        [ -n "$JAVA_FULLVERSION" ] && echologverbose 'Found incomplete installation of : $2' "$JAVA_FULLVERSION"   
    elif [ $retval -eq 1 ] ; then 
        # wrong version
        #
        [ -n "$JAVA_FULLVERSION" ] && echologverbose 'Found $2 at $3' "$JAVA_FULLVERSION" "$JAVA_HOME"
    
    fi
    
    unset OUT
    
    return $retval
}


# Gets the absolute directory
# $1 - the input directory
getPathName() {
    arg="$1"
    saveDir=`$CMD_PWD`
    if [ -d "$arg" ] ; then # Is a directory
        cd $arg
        ret=`$CMD_PWD`
    elif [ -f "$arg" ] ; then # Is a file
        cd `$CMD_DIRNAME $arg`
        ret=`$CMD_PWD`/`$CMD_BASENAME $arg`
    else
        ret="$1"
    fi
    cd $saveDir

    $CMD_ECHO `$CMD_ECHO $ret | $CMD_SED -e 's/\/\//\//'`
}

# Gets the absolute directory (relocatable or otherwise)
# $1 - the input directory
getRelocPathName() {
    ret=`getPathName $1`
    if [ "$RELOCATED_ROOT" != "" ]; then
	if [ "$ret" = "/" ]; then
	    ret="$RELOCATED_ROOT"
	else
	    ret="$RELOCATED_ROOT/$ret"
	fi
    fi

    $CMD_ECHO `$CMD_ECHO $ret | $CMD_SED -e 's/\/\//\//'`
}

# simple function to check if string $2 OR $4 / $2 AND $4 are present in string $1
#return 0
checkString() {
$CMD_ECHO "$1" | $CMD_GREP "$2" > /dev/null 2>&1
ret=$?
if [ -z "$3" ] ; then
    return $ret
else
    operator=$3
    optstring=$4
    [ "$operator" = "OR" ] && [ $ret -eq 0 ] && return $ret
    $CMD_ECHO "$1" | $CMD_GREP "$optstring" > /dev/null 2>&1
    return $?
fi
}


# returns 0 if the required shared library and link(s) are present in $XML_LIB_DIR.
# 1 if not present
#
checkXmlLibDir() {
    OSREV=`${CMD_UNAME} -r| /usr/bin/cut -d. -f2`
    [ $OSREV -gt 9 ] && return 0  # Use bundled libxml libraries for S10 and above
    [ ! -d "$XML_LIB_DIR" ] && return 1
    if [ $USE_LIBXML2 -eq 1 ] ; then
        [ ! -f "$XML_LIB_DIR/$XML_LIB" -o ! -h "$XML_LIB_DIR/$XML_LINK" -o ! -h "$XML_LIB_DIR/$XML_LINK2" ] && return 1
    else    #libxerces
        [ ! -f "$XML_LIB_DIR/$XML_LIB" -o ! -h "$XML_LIB_DIR/$XML_LINK" ] && return 1
    fi
    export XML_LIB_DIR
    return 0
}


# returns 0 if all the required APIs are present in $API_DIR. Reads $XML_API_DIR
# 1 if not present
#
checkXmlApiDir() {
    [ ! -d "$XML_API_DIR" ] && return 1
    API_CREATE_REGISTRY="$XML_API_DIR/createDocument"
    API_INSERT_TAG="$XML_API_DIR/insertTag"    
    API_QUERY_REGISTRY="$XML_API_DIR/queryXml"
    API_SET_ATTRIBUTE="$XML_API_DIR/setAttribute"
    API_REMOVE_TAG="$XML_API_DIR/removeTag"
   
    if [ ! -x "$API_CREATE_REGISTRY" -o ! -x "$API_INSERT_TAG" -o ! -x "$API_QUERY_REGISTRY" -o ! -x "$API_SET_ATTRIBUTE" -o ! -x "$API_REMOVE_TAG" ] ; then
        return 1
    else
        export XML_API_DIR
        export API_CREATE_REGISTRY API_INSERT_TAG API_QUERY_REGISTRY API_SET_ATTRIBUTE API_REMOVE_TAG
        return 0
    fi
}

#set common vars related to the Registry
#
setRegistryVars() {

    COPY_APIS=0
    COPY_LIB=0
    REGISTRY=""
    if [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ] ; then
        HOST=`$CMD_HOSTNAME`
    else
	# If the relocated root dir is from another system, get host name
	$CMD_CAT /etc/mnttab | ${CMD_GREP} $RELOCATED_ROOT | /bin/grep -w nfs > /dev/null 2>&1
	if [ $? -eq 0 ]; then
	    HOST=`$CMD_CAT /etc/mnttab | ${CMD_GREP} $RELOCATED_ROOT | $CMD_CUT -d: -f1 | $CMD_HEAD -1`
	else
	    # else the relocation is local
	    HOST=`$CMD_HOSTNAME`
	fi
        $CMD_PING $HOST > /dev/null 2> /dev/null
        if [ $? -ne 0 -o -z "$HOST" ] ; then
            HOST="localhost"
            echolog 'WARNING: Cannot determine the hostname on $2' "$RELOCATED_ROOT"
            echolog 'Using default registry name Registry_localhost.xml'
        fi
    fi
    
    #comment any *one* of the lines below 
    #
    #USE_LIBXML2=0  #will use libxerces
    USE_LIBXML2=1
    
    if [ $USE_LIBXML2 -eq 1 ] ; then
        XML_LIB="libxml2.so.2.4.12"
        XML_LINK="libxml2.so"
        XML_LINK2="libxml2.so.2"
    else    #libxerces
        XML_LIB="libxerces-c1_1.so.1.0"
        XML_LINK="libxerces-c1_1.so"
    fi
    
    # check if registry home file is already present - 1st priority
    #
    $CMD_PKGINFO $RELOC_PARAM -qi SUNWescom >/dev/null 2>&1
    if [ $? -eq 0 ] ; then            
        basedir=`$CMD_PKGPARAM $RELOC_PARAM SUNWescom BASEDIR`
        productdir=`$CMD_PKGPARAM $RELOC_PARAM SUNWescom PRODUCTDIR`
        [ -z "$ESROOT" ] && ESROOT=`echo $basedir/$productdir | sed 's/\/\/*/\//g'`
        REGISTRY_HOME_FILE="$RELOCATED_ROOT/$ESROOT/.registry_home"
        [ -f "$REGISTRY_HOME_FILE" ] && REGISTRY=$RELOCATED_ROOT`$CMD_CAT $REGISTRY_HOME_FILE`                       
        REGISTRY=`echo $REGISTRY | sed 's/\/\/*/\//g'`
    fi
    
    [ -z "$VAROPTDIR" ] && set_commondirs "$RELOCATED_ROOT"
    [ -z "$LOGDIR" ] && LOGDIR="$VAROPTDIR/install" 
    [ ! -d "$LOGDIR" ] && $CMD_MKDIR -p $LOGDIR

    # if registry home file is not present, use $HOST value - 2nd priority
    #
    if [ -z "$REGISTRY" ] ; then        
        REGISTRY="$LOGDIR/Registry_${HOST}.xml"    
    fi
        
    if [ $FOR_INSTALL -ne 1 -a ! -f "$REGISTRY" ] ; then
        echolog ''
        echolog 'Could not find the Registry file: $2' "$REGISTRY"
        exit_SunMC "$REGISTRY_READ_ERROR"
    fi

    export CURRENT_XML_LIBRARY ESROOT VAROPTDIR LOGDIR REGISTRY REGISTRY_HOME_FILE
    if [ -z "$RELOCATED_ROOT" -o "$RELOCATED_ROOT" = "/" ] ; then
        tmp_osvers=`${CMD_UNAME} -r`    
        tmp_osarch=`${CMD_UNAME} -p`    
        case $tmp_osvers in
	    5.6*)   tmp_osvers=2.6; xml_osvers=2.6  ;;
	    5.7*)   tmp_osvers=2.7; xml_osvers=2.7  ;;
	    5.8*)   tmp_osvers=2.8; xml_osvers=2.8  ;;
	    5.9*)   tmp_osvers=2.9; xml_osvers=2.9  ;;
	    5.10*)   tmp_osvers=2.10; xml_osvers=2.9  ;;
	    *)      echolog 'Unsupported OS version: $2' "$tmp_osvers"
	            exit_SunMC	    ;;
        esac
    else
        case $OSVERS in            
	    5.6*)   tmp_osvers=2.6   ;;
	    2.6*)   tmp_osvers=2.6   ;;
	    6)      tmp_osvers=2.6   ;;
	    5.7*)   tmp_osvers=2.7   ;;
	    2.7*)   tmp_osvers=2.7   ;;
	    7)      tmp_osvers=2.7   ;;
	    5.8*)   tmp_osvers=2.8   ;;
	    2.8*)   tmp_osvers=2.8   ;;
	    8)      tmp_osvers=2.8   ;;
	    5.9*)   tmp_osvers=2.9   ;;
	    2.9*)   tmp_osvers=2.9   ;;
	    9)      tmp_osvers=2.9   ;;	    
	    5.10*)   tmp_osvers=2.10   ;;
	    2.10*)   tmp_osvers=2.10   ;;
	    10)      tmp_osvers=2.10   ;;	    
	    *)      echolog ''
		    echolog 'Unsupported OS version: $2' "$OSVERS"
	            exit_SunMC "$OS_ERROR"   ;;
        esac
       
        # NOTE: need to ask question about architecture of related machine 
        #       for now assume arch is sparc to ensure relocated sparc install works
        #tmp_osarch="sparc"
        xml_osvers=`${CMD_UNAME} -r`    
        tmp_osarch=`${CMD_UNAME} -p`    
        case $xml_osvers in
            5.6*)   xml_osvers=2.6   ;;
            5.7*)   xml_osvers=2.7   ;;
            5.8*)   xml_osvers=2.8   ;;
            5.9*)   xml_osvers=2.9   ;;
            5.10*)  xml_osvers=2.9   ;;
            *)      echolog ''
                    echolog 'Unsupported OS version: $2' "$xml_osvers"
                    exit_SunMC "$OS_ERROR"   ;;
        esac
        
    fi

    # Std solaris names are Solaris_2.6 Solaris_7 Solaris_8 Solaris_9
    # Please note the difference for Solaris 2.6  
    # 
    std_tmp_osvers=`/usr/bin/echo ${xml_osvers} | /usr/bin/cut -d"." -f2 | sed 's/^6/2.6/' `
    XML_LIB_DIR="$ESROOT/base/lib/${tmp_osarch}-sun-solaris${xml_osvers}"
    XML_API_DIR="$ESROOT/base/bin/${tmp_osarch}-sun-solaris${xml_osvers}"  

    tmp_xml_dir="${RELOC_DIR}/${TMP_DIR}/XML" #Just in case the APIs are found here

}


#xerces and libxml2 will co-exist until the code changes are 
#complete and stable

initializeRegistry() {

    if [ "$1" = "FOR_INSTALL" ] ; then
        FOR_INSTALL=1
    else
        FOR_INSTALL=0 
    fi

    setRegistryVars
    
    #check if XML library must be copied to /tmp/SunMCInstall
    #
    checkXmlLibDir
    if [ $? -eq 1 ] ; then
        XML_LIB_DIR="$tmp_xml_dir"
        checkXmlLibDir   #just in case they are here already
        if [ $? -eq 1 ] ; then
            [ $FOR_INSTALL -eq 0 ] && exit_SunMC "$XML_INITIALIZATION_ERROR" 
            COPY_LIB=1            
        fi
    fi
    
    #check if XML APIs must be copied to /tmp/SunMCInstall
    #
    checkXmlApiDir
    if [ $? -eq 1 ] ; then
        XML_API_DIR="$tmp_xml_dir/APIs"
        checkXmlApiDir  #just in case they are here already
        if [ $? -eq 1 ] ; then
            [ $FOR_INSTALL -eq 0 ] && exit_SunMC "$XML_INITIALIZATION_ERROR"
            COPY_APIS=1            
        fi
    fi

    [ $COPY_LIB -eq 1 -o $COPY_APIS -eq 1 ] && copyLibApis
 
    #now we have copied everything that was needed. Set paths appropriately
    #
    checkString "$PATH" "$XML_API_DIR"
    if [ $? -ne 0 ] ; then
        PATH="$PATH:$XML_API_DIR"
        export PATH
    fi
    
    checkString "$LD_LIBRARY_PATH" "$XML_LIB_DIR"
    if [ $? -ne 0 ] ; then
        LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${COMMAND_ROOT}/usr/lib:${RELOC_DIR}/usr/lib:$XML_LIB_DIR"
        export LD_LIBRARY_PATH
    fi

    unset COPY_APIS COPY_LIB XML_LIB XML_LINK XML_LINK2 tmp_xml_dir
   
    setRegistry 
}

copyLibApis() {

    #called by inst, but we need to have access to image
      
    [ -z "$SCRIPT_DIR" ] && SCRIPT_DIR=`/usr/bin/dirname $0`
    prev_dir=`/usr/bin/pwd`
    cd $SCRIPT_DIR
    l_dir=`/usr/bin/pwd`        
        
    check_if_called_from_disk_image
    if [ $? -ne 0 ] ; then # not called from disk image          
        check_if_called_from_installed_place
        if [ $? -eq 0 ] ; then # called from installed place	        
            echolog 'XML APIs and / or shared object library are not accessible'
            echolog 'You must install from a CD or disk image so that install may copy the required files to your system'
            exit_SunMC "$XML_INITIALIZATION_ERROR"                 
        fi                     
    fi
    cd $prev_dir
    unset prev_dir l_dir
     
    if [ $COPY_LIB -eq 1 ] ; then     
        SRC_LIB_DIR="${SCRIPT_DIR}/lib/${tmp_osarch}-sun-solaris${std_tmp_osvers}"
        if [ ! -d "$SRC_LIB_DIR" ] ; then
            echolog 'XML shared object library not accessible'
            exit_SunMC "$XML_INITIALIZATION_ERROR"
        fi
           
        $CMD_MKDIR -p "$XML_LIB_DIR" > /dev/null 2>&1
        if [ $? -ne 0 ] ; then
            echolog 'Can not create the directory $2' "$XML_LIB_DIR"
            exit_SunMC "$XML_INITIALIZATION_ERROR"            
        fi 
        
        echologverbose '    Copying required XML library from $2 to $3' "$SRC_LIB_DIR" "$XML_LIB_DIR"
            
        $CMD_CP -Rf "${SRC_LIB_DIR}/${XML_LIB}" "${XML_LIB_DIR}/${XML_LIB}" > /dev/null 2>&1            
        if [ $? -ne 0 ] ; then
            echolog 'Can not copy the required files to $2' "$XML_LIB_DIR"
            exit_SunMC "$XML_INITIALIZATION_ERROR"
        fi          
         
        $CMD_LN -fs "${XML_LIB_DIR}/${XML_LIB}" "${XML_LIB_DIR}/${XML_LINK}"
        if [ $? -ne 0 ] ; then
            echolog 'Can not create required link: $2 in $3' "${XML_LINK}" "$XML_LIB_DIR" 
            exit_SunMC "$XML_INITIALIZATION_ERROR"
        fi
        
        if [ $USE_LIBXML2 -eq 1 ] ; then            
            $CMD_LN -fs "${XML_LIB_DIR}/${XML_LIB}" "${XML_LIB_DIR}/${XML_LINK2}"
            if [ $? -ne 0 ] ; then
                echolog 'Can not create required link: $2 in $3' "${XML_LINK2}" "$XML_LIB_DIR"
                exit_SunMC "$XML_INITIALIZATION_ERROR"
            fi
        fi
    fi
    
    if [ $COPY_APIS -eq 1 ] ; then
        SRC_API_DIR="${SCRIPT_DIR}/bin/${tmp_osarch}-sun-solaris${std_tmp_osvers}"
        if [ ! -d "$SRC_API_DIR" ] ; then
            echolog 'XML APIs not accessible' 
            exit_SunMC "$XML_INITIALIZATION_ERROR"
        fi
    
        $CMD_MKDIR -p "$XML_API_DIR" > /dev/null 2>&1
        if [ $? -ne 0 ] ; then
            echolog 'Can not create the directory $2' "$XML_API_DIR"
            exit_SunMC "$XML_INITIALIZATION_ERROR"
        fi 
         
        echologverbose '    Copying required XML APIs from $2 to $3' "$SRC_API_DIR" "$XML_API_DIR"
        $CMD_CP -Rf ${SRC_API_DIR}/* $XML_API_DIR > /dev/null 2>&1
        
        checkXmlApiDir
        if [ $? -ne 0 ] ; then
            echolog 'Error copying XML APIs to $2' "$XML_API_DIR"
            exit_SunMC "$XML_INITIALIZATION_ERROR"
        fi         
    fi  

}


setRegistry() {
    if [ -z "$OSVERSION"  ]; then
	OSVERSION=`${CMD_UNAME} -r`
    fi
    case $OSVERSION in
	5.6*)   OSVERSION=2.6   ;;
	5.7*)   OSVERSION=2.7   ;;
	5.8*)   OSVERSION=2.8   ;;
	5.9*)   OSVERSION=2.9   ;;
	5.10*)  OSVERSION=2.10   ;;
	*)      echolog ''
		echolog 'Unsupported OS version: $2' "$OSVERSION"
		exit_SunMC "$OS_ERROR"   ;;
    esac

    if [ ! -f "$REGISTRY"  ] ; then        

        [ $FOR_INSTALL -eq 0 ] && return $REGISTRY_MISSING_ERROR
   
        $API_CREATE_REGISTRY "$REGISTRY" "registry" > /dev/null 2>&1

        $CMD_CHMOD 644 "$REGISTRY"
        if [ $? -ne 0 ] ; then
            echolog ''
            echolog 'Unable to create Registry $2.' "$REGISTRY"
            echolog ''
            exit_SunMC "$REGISTRY_PERMISSION_ERROR"
        fi

        $API_INSERT_TAG "$REGISTRY" "category=SunMC" > /dev/null 2>&1        
        $API_INSERT_TAG "$REGISTRY" "category=Installation" > /dev/null 2>&1   
        $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "osvers=${OSVERSION}" > /dev/null 2>&1    

        # Record old version of sunmc in case of upgrade
        #
        if [ ! -z "$INSTALLED_PKGVER" ] ; then
           $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "oldversion=${INSTALLED_PKGVER}" > /dev/null 2>&1    
        fi
       
     else
        #check if the OS version has been changed since the Registry was created.
        reg_os=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "osvers"  2>/dev/null`
        if [ -z "$reg_os" ] ; then
            echologverbose 'WARNING:'
            echologverbose 'The Solaris OS version was not recorded when installing Sun Management Center 3.5 Update 1.'
            echologverbose 'Your machine is currently running : $2' "${tmp_osvers}"
            echologverbose ''
            echologverbose ''
            $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "osvers=${OSVERSION}" > /dev/null 2>&1    
        elif [ "$reg_os" != "${OSVERSION}" ] ; then
            echolog 'The Solaris OS version when installing Sun Management Center 3.5 Update 1. was : $2' "$reg_os"
            echolog 'Your machine is currently running : $2' "${OSVERSION}"
            echolog 'Cannot proceed with current task. Exiting.'
            exit_SunMC $OS_ERROR
        fi
    fi
    
    unset tmp_osvers FOR_INSTALL 
    
}



# Finds all products installed from Registry
# Input: $1 => install-status to be queried from registry
#             Uninstall will call this with 
# Returns : - Sets L_INSTALLED_PRODUCTS => "PROD1 PROD2 ..."
#             PROD1 in the list will be BASE_PRODUCT
#           - Sets L_INSTALLED_PRODUCTS
#
get_installed_products_from_registry() {

   
   BASE_PRODUCT="PRODUCT.PE"
   
   
   L_INSTALLED_PRODUCTS=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product" "key" WHERE "install-status=1" 2> /dev/null `
   [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
 
   if [ -z "L_INSTALLED_PRODUCTS" ]; then
      echolog 'BAD Registry. '
      exit_SunMC "$REGISTRY_READ_ERROR"
   else
      L_INSTALLED_PRODUCTS=`$CMD_ECHO $L_INSTALLED_PRODUCTS | /usr/bin/sed "s/,/ /g"`
      L_INSTALLED_ADDONS=`$CMD_ECHO $L_INSTALLED_PRODUCTS | /usr/bin/sed "s/"PRODUCT.PE"//"`
   fi
   
}


# Finds all dependant products for all in a given list of products 
# Input: $1 - product ID for which dependant products to be found 
#           - Also reads L_INSTALLED_PRODUCTS
# Returns : - echos list of dependant products on $1
#
get_dependant_products () {   

   for each_product in $L_INSTALLED_PRODUCTS
   do      
      
      depends_on=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "depends-on"  2> /dev/null `
      [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
      #depends_on=`getValueFromRegistry "PRODUCT.$each_product.DEPENDS_ON" `
      
      $CMD_ECHO $depends_on | $CMD_GREP $1 > /dev/null 2>&1
      [ $? -eq 0 ] &&  dependant_products="$dependant_products $each_product"
   done

   $CMD_ECHO $dependant_products

   unset depends_on dependant_products  

}

# Depending on setup status in Registry file,
# Returns : sets flags server_setup,metadata_setup, serveces_setup, console_setup agent_setup  & database_setup
# Input:None
# CHANGED
set_setup_flags () {
      
      server_setup=0
      services_setup=0
      agent_setup=0
      metadata_setup=0
      console_setup=0
      
      L_BASE_SETUP_LAYERS=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer" "key" WHERE "setup-status=1" 2> /dev/null `
      [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"

      temp_str=`/usr/bin/echo $L_BASE_SETUP_LAYERS | /usr/bin/grep -w SERVER`
      [ "$temp_str" ] && server_setup=1 && metadata_setup=1 && services_setup=1
      
      temp_str=`/usr/bin/echo $L_BASE_SETUP_LAYERS | /usr/bin/grep -w AGENT `
      [ "$temp_str" ] && agent_setup=1
      
      temp_str=`/usr/bin/echo $L_BASE_SETUP_LAYERS | /usr/bin/grep -w CONSOLE `
      [ "$temp_str" ] && console_setup=1
      
      # Set BASE_SETUP_COMPLETE flag if setup is complete for all the installed layers
      #
      BASE_SETUP_COMPLETE=1
      [ "$no_server" = "0" -a "$server_setup" != "1" ] && BASE_SETUP_COMPLETE=0
      [ "$no_agent" = "0" -a "$agent_setup" != "1" ] && BASE_SETUP_COMPLETE=0
      [ "$no_console" = "0" -a "$console_setup" != "1" ] && BASE_SETUP_COMPLETE=0
      export BASE_SETUP_COMPLETE

      database_setup=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_setup"  2> /dev/null `
      [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
      
}


# Get products which are not yet setup from Registry
# Addon Product will be treated as if setup if no setup script 
# is present for then
# Input $1 = sort_flag = if 1 then sorts in order of dependancies.  
# This returns 
#          - L_ADDONS_NOT_SETUP => "BASE_PROD ADDON1 ADDON2 ..."
#            THIS LIST WILL BE IN OREDER OF **DEPENDANCIES**
#              
get_setup_addons_from_registry() {
   
   L_ADDONS_NOT_SETUP=""
   L_ADDONS_SETUP=""
   
   L_ADDONS_NOT_SETUP=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product" "key" WHERE "setup-status=0" 2> /dev/null`
   [ $? -gt 0 ] &&  exit_SunMC "$REGISTRY_READ_ERROR"
   L_ADDONS_SETUP=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product" "key" WHERE "setup-status=1" 2> /dev/null`
   [ $? -gt 0 ] &&  exit_SunMC "$REGISTRY_READ_ERROR"

   # Remove delimiters & BASEPRODUCT from list
   #
   L_ADDONS_SETUP=`/usr/bin/echo $L_ADDONS_SETUP | /usr/bin/sed 's/,/ /g'`
   L_ADDONS_NOT_SETUP=`/usr/bin/echo $L_ADDONS_NOT_SETUP | /usr/bin/sed 's/,/ /g'`
   L_ADDONS_SETUP=`$CMD_ECHO $L_ADDONS_SETUP | /usr/bin/sed "s/"PRODUCT.PE"//"`
   L_ADDONS_NOT_SETUP=`$CMD_ECHO $L_ADDONS_NOT_SETUP | /usr/bin/sed "s/"PRODUCT.PE"//"`
    
   # Sort all unsetup products in order of dependancies
   #
   L_TEMP=""
   while [ "$L_TEMP" != "$L_ADDONS_NOT_SETUP" ]
   do         
      L_SORTED=""
      L_TEMP="$L_ADDONS_NOT_SETUP"
      for each_product in $L_ADDONS_NOT_SETUP
      do
         L_TEMP2=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "depends-on"  2> /dev/null`
         [ $? -gt 0 ] &&  exit_SunMC "$REGISTRY_READ_ERROR"
         #L_TEMP2=`getValueFromRegistry "PRODUCT.$each_product.DEPENDS_ON"`
         L_TEMP2=`/usr/bin/echo $L_TEMP2 | /usr/bin/sed 's/,/ /g'`

         for each_temp in $L_TEMP2
         do  
            /usr/bin/echo $L_ADDONS_NOT_SETUP | /usr/bin/grep $each_temp > /dev/null
            if [ $? -eq 0 ] ; then
                /usr/bin/echo $L_SORTED | /usr/bin/grep $each_temp > /dev/null
                [ $? -gt 0 ] && L_SORTED="$L_SORTED $each_temp"
            fi
         done
         /usr/bin/echo $L_SORTED | /usr/bin/grep $each_product > /dev/null
         [ $? -gt 0 ] && L_SORTED="$L_SORTED $each_product"      
      done
      L_ADDONS_NOT_SETUP="$L_SORTED"
   done
         
   unset setup_status temp_prod_list L_TEMP L_TEMP2 L_SORTED

}


# This will check existing SunMC setup
# 
get_SunMC_setup_status () {

   get_SunMC_install_status

   # Returns : L_ADDONS_NOT_SETUP => "ADDON1 ADDON2 ..."  
   # in order of **DEPENDANCIES**
   # 
   get_setup_addons_from_registry 

   # This sets all components which are handled as increamental setup
   # This sets server_setup, console_setup agent_setup & database_setup
   # also sets L_BASE_SETUP_LAYERS
   #
   set_setup_flags

}


# This will check existing SunMC install setup
# 
get_SunMC_install_status() {
   
   # Find L_INSTALLED_PRODUCTS,L_INSTALLED_ADDONS
   #
   get_installed_products_from_registry   
   
   # This sets all flags to indicate base_product inst status
   # no_server,no_agent,no_console
   set_inst_flags

}

# Input $1: List of product IDs
# returns : echos list containing names of product ID's instead of ID's in 
#           same sequence. 
get_product_names() {

   temp_list=""
   
   for each_addon in `$CMD_ECHO $1 | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do
      temp_name=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "name" 2> /dev/null `
      if [ $? -gt 0 ]; then
         temp_list="$temp_list,$each_addon"
      else
         if [ "$temp_name" = "Production Environment" ] ; then
           [ "$no_DE" = "0" ] && temp_name="Developer Environment"
         fi
         temp_list="$temp_list,$temp_name"
      fi
   done

   temp_list=`/usr/bin/echo $temp_list | /usr/bin/sed 's/,/ /'`

   /usr/bin/echo "$temp_list"

   unset temp_list temp_name

}



# << END Registry related functions<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #


# << BEGIN functions related to read user input - from summary file /console<<<<<<<<<<<< #

# This function is intended for use of base product only.
# The function expects AUTOCONFIG_RUNFILE and AUTOCONFIG_SAVEFILE variables to 
# be absolute path names. User provided filename must be converted to absolute  
# absolute pathmanes before calling this function. 
#
setup_response_summary() {

    if [ ! -z "$AUTOCONFIG_RUNFILE" ]; then
        if [ ! -r "$AUTOCONFIG_RUNFILE" ]; then
             echolog ''
             echolog 'Can not read response file: $2' "$AUTOCONFIG_RUNFILE"
             [ $flash_questions_to_console -eq 0 ] && exit_SunMC "$SUMMARY_READ_ERROR"
             echolog 'This script will redirect all questions to console.'
             unset AUTOCONFIG_RUNFILE
             checkString "$PROGNAME" "es-inst"             
             [ $? -eq 0 ] && continueAfterConfirm	     
        else
             # In case user provides same file as argument to -A and -C option, 
             # give  presedence to AUTOCONFIG_SAVEFILE 
             if [ "$AUTOCONFIG_SAVEFILE" = "$AUTOCONFIG_RUNFILE" ]; then
                 echolog 'WARNING: AUTOCONFIG_SAVEFILE and AUTOCONFIG_RUNFILE can not be same.' 
                 echolog '-A option will be ignored.'
                 unset AUTOCONFIG_RUNFILE
             else              
                 export AUTOCONFIG_RUNFILE
             fi
        fi
    fi

    if [ ! -z "$AUTOCONFIG_SAVEFILE" ]; then
        $CMD_TOUCH "$AUTOCONFIG_SAVEFILE"
        if [ $? -ne 0 ] ; then
           echolog ''
           echolog 'Can not write to response file: $2' "$AUTOCONFIG_SAVEFILE"  
           unset AUTOCONFIG_SAVEFILE
        else
           export AUTOCONFIG_SAVEFILE
        fi
    fi

    # This part checks if the response file is generated by image tool
    # If yes, it will set AGENTUPDATE_FLAG to TRUE

    if [ -f "$AUTOCONFIG_RUNFILE" ]; then
        agentupdate_flag=`getAutoConfig "RESPONSES_FOR_AGENT_UPDATE"`
        SETUP_AGENTUPDATE_FLAG="$agentupdate_flag"
        export SETUP_AGENTUPDATE_FLAG
    fi

}

# Inputs : Reads AUTOCONFIG_RUNFILE READ_RESPONSE_ONCE flash_questions_to_console
# Returns : answer - /summary file / console
#
fetch_response_yes_no() {
    
    old_text_domain="ES_SCRIPTS"
    [ ! -z "$TEXTDOMAIN" ] && old_text_domain="$TEXTDOMAIN"

    checkString "$1" "TAG="
    [ $? -eq 0 ] && tag=`$CMD_ECHO "$1" | $CMD_SED "s/TAG=//"` && shift
    qn_str=$1 && shift
    runtime_vars=""
    [ $# -gt 0 ] && runtime_vars="$@"  
    answer_argument_no="$#"
    answer_argument_no=`/usr/bin/expr "$answer_argument_no" + 3 2> /dev/null `

    if [ -n "$AUTOCONFIG_RUNFILE" ] ; then  
       if [ "$READ_RESPONSE_ONCE" = "0" ] ; then
          READ_RESPONSE_ONCE=1
          answer=`getAutoConfig "$tag"`

          if [ "$PROGNAME" != "archive-tool" ] ; then
             echolog "$qn_str \$${answer_argument_no}" " " $runtime_vars" : $answer"
          fi
               
          if [ -n "$answer" ]; then
             [ $answer -ne 0 -a $answer -ne 1 ] && exit_SunMC "$SUMMARY_READ_ERROR"               
             return 0
          else
             if [ "$PROGNAME" != "archive-tool" ] ; then
                setup_textdomain ES_SCRIPTS
                echolog 'TAG missing/empty from summary file:$2' "$tag" 
                setup_textdomain "$old_text_domain"
             fi
          fi           
            
       elif [ "$flash_questions_to_console" = "0" ]; then
           setup_textdomain ES_SCRIPTS
           echolog 'TAG missing/empty from summary file:$2' "$tag"
           setup_textdomain "$old_text_domain"
           return "$SUMMARY_READ_ERROR"
       fi   
    fi
    
    if [ "$flash_questions_to_console" != "0" ]; then
       ask_user "$qn_str" "" $runtime_vars
       return 0
    fi
    return 1   
}

# Inputs : Reads AUTOCONFIG_RUNFILE READ_RESPONSE_ONCE flash_questions_to_console
# Returns : answer - /summary file / console
#
fetch_response_text() {

    old_text_domain="ES_SCRIPTS"
    [ ! -z "$TEXTDOMAIN" ] && old_text_domain="$TEXTDOMAIN"
    
    checkString "$1" "TAG="
    [ $? -eq 0 ] && tag=`$CMD_ECHO "$1" | $CMD_SED "s/TAG=//"` && shift
    qn_str=$1 && shift
    runtime_vars=""
    [ $# -gt 0 ] && runtime_vars="$@"
    answer_argument_no="$#"
    answer_argument_no=`/usr/bin/expr "$answer_argument_no" + 3 2> /dev/null `
      
    if [ -n "$AUTOCONFIG_RUNFILE" ] ; then
        if [ "$READ_RESPONSE_ONCE" = "0" ]; then
           READ_RESPONSE_ONCE=1
           answer=`getAutoConfig "$tag"`
           [ -n "$answer" ] && echolog "$qn_str \$${answer_argument_no}" " " $runtime_vars " : $answer" && return 0
        elif [ "$flash_questions_to_console" = "0" ]; then
            setup_textdomain ES_SCRIPTS
            echolog 'TAG missing/empty from summary file:$2' "$tag"
            setup_textdomain "$old_text_domain"
            return "$SUMMARY_READ_ERROR"
        fi
    fi
    
    setup_textdomain "$old_text_domain"
    if [ "$flash_questions_to_console" != "0" ] ; then
        get_input_from_user "$qn_str" "" $runtime_vars
        return 0
    fi
    return 1   
}


# << END functions related to read user input - from summary file /console<<<<<<<<<<<< #


validate_registry() {

   R_count=`/usr/bin/cat $REGISTRY | grep "<package" | wc -l`
   S_count=`/usr/bin/pkginfo -c symon | wc -l`

   if [ $R_count -eq $S_count ]; then
      echolog  'Total packages in Registry & System are same = $2 ' "$R_count"
      return 0
   else
      if [ $R_count -gt $S_count ]; then
          diff=`expr $R_count - $S_count`
          echolog 'Registry shows $2 more packages then system -  $3' "$diff" "$S_count"
          return 1
      else
          diff=`expr $S_count - $R_count`
          echo 'System has  $2 more packages then Registry - $3' "$diff" "$R_count"
          return 1
      fi
   fi
}


checkJavaForGUI() {
    FOR_WIZARD=1
    checkJavaOK
    return $?
    
}
#this is used to get the correct property jar file for different locale
getPropLocale() {

    Language=${LANG}
    if [ -n "$Language" ] && [ "$Language" != "C" ]; then
        Is_zh_TW=`/usr/bin/expr "$Language" : '\(zh_TW\).*'`
        if [ "$Is_zh_TW" = "zh_TW" ]; then
            PropLocale="zh_TW"
            export $PropLocale
        else
            PropLocale=`/usr/bin/expr "$Language" : '\(..\).*'`
            export $PropLocale
        fi
    fi

}

#This is to find out whether an optional component has been selected or not.
#This function is primarily for Addons integrating with Agent Update feature.
#Function call : isComponentSelected <PROD_KEY> <COMP_KEY>
#Then check for $?
#Return status : 0 if selected
#              : 1 if not selected

isComponentSelected () {
    tmp_prodkey="$1"
    tmp_compkey="$2"

    tmp_all_optionals="${ALL_SELECTED_OPTIONALS}"

    checkString "${tmp_all_optionals}" "${tmp_prodkey}:${tmp_compkey}"
    ret=$?
    unset tmp_prodkey tmp_compkey tmp_all_optionals
  
    return $ret
}

guiScriptsOptArgErrorAndExit () {

    echo " "
    echo "     \c"
    echolog '$2 does not support any options or arguments.' `$CMD_BASENAME $PROGNAME"`
    echo "     \c"
    echolog "Exiting..."
    echo " "
    exit 1
}

# rmdir_if_empty $dir
# - recursively removes all empty directories from $dir, including $dir itself
#   if it is empty after the removal.
rmdir_if_empty () {
    # Return if nothing to do
    [ ! -d "$1" ] && return 0

    dirs=`/usr/bin/find $1 -depth -type d`
    for dir in $dirs ; do
        $CMD_RMDIR $dir >/dev/null 2>&1
    done
    return 0
}

addLicensePack () {

    licenseline="$1"
    licfile=$VARDIR/.license.packs

    addline=0
    if [ -f "$licfile" ] ; then
        found=`$CMD_GREP -e "$licenseline" $licfile 2>/dev/null`
        if [ $? -ne 0 ] ; then
            addline=1   
        fi
    else
        addline=1
    fi

    if [ $addline -eq 1 ] ; then
        /bin/echo "$licenseline" >> ${VARDIR}/.license.packs
        ${CMD_CHMOD} 444 ${VARDIR}/.license.packs
    fi

    return 0
}

removeLicensePack () {
    licenseline="$1"
    licfile=$VARDIR/.license.packs

    if [ -f $licfile ] ; then
        ${CMD_GREP} -v "^$licenseline" ${VARDIR}/.license.packs > ${VARDIR}/.license.packs.new
        /usr/bin/mv ${VARDIR}/.license.packs.new ${VARDIR}/.license.packs
    fi
}

#
# must be called by an AddOn setup that requires Lockhart
# Authentication plug-in to be setup.
#
setupWebConsoleLinks () {
    # check for common console Installation
    /usr/bin/pkginfo -q SUNWmcon
    if [ $? -ne 0 ] ; then
        echolog "The Sun Web Console package is not installed."
        multiline_echolog "Can not setup Sun Management Center authentication module\nuntil SUNWmcon package is installed."
        return 1
    fi
    
    WEBCONSOLE=/usr/sadm/lib/webconsole
    RTRC=/usr/lib/webconsole/.runtimerc
    if [ ! -f "$RTRC" ]
    then
        return 0
    fi
    . ${RTRC}

    SMREG=/usr/sbin/smreg
    if [ ! -f ${SMREG} ]; then
        echolog "The Sun Web Console package is not installed."
        multiline_echolog "Can not setup Sun Management Center authentication module\nuntil SUNWmcon package is installed."
        return 1
    fi
    #
    # If the link is there and the module is registered then do
    # nothing and simply return
    #
    if [ -h ${CATALINA_HOME}/lib/esclt.jar -a \
	 -h ${CATALINA_HOME}/lib/esjrm.jar -a \
	 -h ${CATALINA_HOME}/lib/escom.jar -a \
	 -h ${CATALINA_HOME}/lib/esmsg.jar -a \
	 -h ${CATALINA_HOME}/lib/smlegacyservices.jar ]; then
	${SMREG} list -m | grep "com\.sun\.management\.services\.authentication\.SMLegacyLoginModule" >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		return 0
	fi
    fi

    set_basedir
    JARS="${BASEDIR}/classes/esclt.jar \
	${BASEDIR}/classes/esjrm.jar \
	${BASEDIR}/classes/escom.jar \
	${BASEDIR}/classes/esmsg.jar \
	/usr/share/webconsole/lib/smlegacyservices.jar"

    for srcJar in ${JARS}
    do
	jarFile=`basename $srcJar`
	targetJar=${CATALINA_HOME}/lib/${jarFile}
	${CMD_RM} ${targetJar} >/dev/null 2>&1
	${CMD_LN} -s ${srcJar} ${targetJar} >/dev/null 2>&1
	if [ $? -ne 0 ]; then
		echolog "Unable to link jars for Sun Web Console"
		return 1
	fi
    done

    if [ -s ${SMREG} ]; then
	${SMREG} remove -m com.sun.management.services.authentication.SMLegacyLoginModule >/dev/null 2>&1
	${SMREG} add -m -b optional com.sun.management.services.authentication.SMLegacyLoginModule >/dev/null 2>&1
    fi
    return 0
}

#
# removeWebConsoleLinks called to unregister SunMC Web Console
# auth. plug-in and remove links 
#

removeWebConsoleLinks () {
    #
    # check for Web console Installation if its not there
    # nothing needs to be done.
    #
    /usr/bin/pkginfo -q SUNWmcon
    if [ $? -ne 0 ] ; then
        return 0
    fi
    
    WEBCONSOLE=/usr/sadm/lib/webconsole
    RTRC=/usr/lib/webconsole/.runtimerc
    if [ ! -f "$RTRC" ]
    then
        return 0
    fi
    . ${RTRC}

    set_basedir
    SMREG=/usr/sbin/smreg
    if [ -s ${SMREG} ]; then
	${SMREG} remove -m com.sun.management.services.authentication.SMLegacyLoginModule >/dev/null 2>&1
    fi

    JARS="esclt.jar esjrm.jar escom.jar esmsg.jar smlegacyservices.jar"
    for jarFile in ${JARS}
    do
	targetJar=${CATALINA_HOME}/lib/${jarFile}
	${CMD_RM} ${targetJar} >/dev/null 2>&1
    done

    return 0
}

#
# Check if system support incoming encrypted message
#
isEncryptInput() {
    #
    # check privOID
    #
    desPrivOID="1.3.6.1.6.3.10.1.2.2"
    oid=`$XGET $VAROPTDIR/cfg/domain-config.x security.privOID`

    if [ "$oid" = "$desPrivOID" ]; then
        return 1
    else
        return 0
    fi
}


#
# Check if system support outbound encrypted message
#
isEncryptOutput() {
    #
    # check privOID
    #
    level=`$XGET $VAROPTDIR/cfg/domain-config.x security.securityLevel`

    if [ "$level" = "priv" ]; then
        return 1
    else
        return 0
    fi
}

#
# Print the encryption supported message.
# This function may be called after running base-usm-seed
#
printEncryptSupportMessage () {
    echolog ""
    echolog ""

    isEncryptInput
    if [ $? -eq 1 ]; then
	multiline_echolog 'Crypt Utilities package (SUNWcry) was found.\nEncrypted SNMP communication is supported.'
    else
	multiline_echolog 'Crypt Utilities package (SUNWcry) was not found.\nEncrypted SNMP communication is not supported.'
    fi

    echolog ""
}

checkDisplayEnvForGUI () {
    set | grep "^DISPLAY=" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo ' '
        echolog 'The DISPLAY environment variable must be set to a valid X server'
        echo ' '
        echo ' '
        return 1
    fi
    return 0
}

# This function configures the agent port with a different logic
# for agent update. Fix : 4840003

configurePortForAgentUpdate () {

    agent_update_port=`getAutoConfig "agent_OPTIONAL_PORT"`
    if [ "$agent_update_port" = "DEFAULT" ]; then
        # The user has selected to either use the existing port
        # or use the default (161) port for fresh install. 

        echologverbose 'The user selected to use the existing or default port for agent update'

        # Check if there is any existing port configuration.
        old_port=`$XGET "$VARDIR/domain-config.x" agent.snmpPort`
        if [ -z "$old_port" ]; then
            # Default to 161
            echologverbose 'Using the default port for agent update'
            agent_update_port=161
        else
            echologverbose 'Using the existing port for agent update'
            agent_update_port=$old_port
        fi
    else
        # use the port as it is given
        echologverbose 'Using the port $2 for agent update' "$agent_update_port"
    fi
    echologverbose 'Updating $2 with new port number.' "$VARDIR/domain-config.x"
   
    [ -x "$XPUT" ] && set_xput
    $XPUT $VARDIR/domain-config.x agent.snmpPort "$agent_update_port"

    # add to L_ALL_SUNMC_PORTS so that the snmpdx check is done correctly.
    L_ALL_SUNMC_PORTS=`$XGET ${TMP_DIR}/sunmc_ports.x ALL_SUNMC_PORTS 2> /dev/null`
    L_ALL_SUNMC_PORTS="$L_ALL_SUNMC_PORTS<$agent_update_port>"
    $XPUT "${TMP_DIR}/sunmc_ports.x" "ALL_SUNMC_PORTS" "$L_ALL_SUNMC_PORTS"

}


########################################################
#
# Version to convert a version string in X.Y.Z-* or
# X.Y.X_NN format to XYZNN format so can be treated as a
# number.
#
# $1 = version string
# Returns numerical version
#
########################################################
versionString2Num () {

    # Minor and micro default to 0 if not specified.
    major=`$CMD_ECHO $1 | $CMD_AWK -F. '{print $1}'`
    minor=`$CMD_ECHO $1 | $CMD_AWK -F. '{print $2}'`
    if [ ! -n "$minor" ]; then
	minor="0"
    fi
    micro=`$CMD_ECHO $1 | $CMD_AWK -F. '{print $3}'`
    if [ ! -n "$micro" ]; then
	micro="0"
    fi

    # The micro version may further be extended to include a patch number.
    # This is typically of the form <micro>_NN, where NN is the 2-digit
    # patch number.  However it can also be of the form <micro>-XX, where
    # XX is some arbitrary non-digit sequence (eg., "rc").  This latter
    # form is typically used for internal-only release candidates or
    # development builds.
    #
    # For these internal builds, we drop the -XX and assume a patch number
    # of "00".	Otherwise, we extract that patch number.
    #
    patch="00"
    dash=`$CMD_ECHO $micro | grep "-"`
    if [ $? -eq 0 ]; then
	# Must be internal build, so drop the trailing variant.
	micro=`echo $micro | $CMD_AWK -F- '{print $1}'`
    fi

    underscore=`echo $micro | grep "_"`
    if [ $? -eq 0 ]; then
	# Extract the seperate micro and patch numbers, ignoring anything
	# after the 2-digit patch.
	patch=`echo $micro | $CMD_AWK -F_ '{print substr($2, 1, 2)}'`
	micro=`echo $micro | $CMD_AWK -F_ '{print $1}'`
    fi

    echo "${major}${minor}${micro}${patch}"

} # versionString2Num


