#!/bin/sh
# Copyright 08/05/05 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident "@(#)es-validate	1.31 05/08/05 Sun Microsystems"


reset_all_validation_flags() {
    LICENSE=FALSE
    PREMIER_PACKAGES=FALSE
    WEBSERVER_PACKAGES=FALSE
    WEBSERVER_CONNECTIVITY=FALSE
    SERVELET_CONNECTIVITY=FALSE
    CLIENT_API=FALSE
    CLI_ALARMS=FALSE
    JAVA_FOUND=N
}


validate_misc_features() {
    return 0
}


validate_functionality_details () {

    echolog ''
    #echolog 'Validating functionality details...'

    USERFILE=/var/opt/SUNWsymon/cfg/esusers
    if [ -r "$USERFILE" ] && [ "$no_server" = "0" ] 
    then
        USERLIST=""
        for each in `/usr/bin/cat $USERFILE`
        do
            if [ "$each" != esmaster ] && [ "$each" != espublic ]
            then
                USERLIST="$USERLIST $each"
            fi
        done
        #echolog ''
        #format_display "$USERLIST"
        #echolog 'Sun Management Center users $2: $3' "\r\t\t\t\t" "$tmp_display_string"
        echolog ''
        echolog 'Privilege level for Sun Management Center users :'
        echolog '-------------------------------------------------------------------------------'
        echolog 'CATEGORY $2 USERS' "\r\t\t\t\t"
        echolog '-------------------------------------------------------------------------------'
 
        tmp_previlege_users=`/usr/bin/grep esadm /etc/group | /usr/bin/cut -f4 -d: 2> /dev/null `
        tmp_previlege_users=`echo $tmp_previlege_users | /usr/bin/sed  "s/,/ /g"  2> /dev/null `
        tmp_previlege_users=`/usr/bin/echo $tmp_previlege_users 2> /dev/null `
        [ -z "$tmp_previlege_users" ] && tmp_previlege_users="None"
        format_display "$tmp_previlege_users"
        echolog '$2 $3: $4' "esadm" "\r\t\t\t\t" "$tmp_display_string"
        
        
        tmp_previlege_users=`/usr/bin/grep esdomadm /etc/group | /usr/bin/cut -f4 -d: 2> /dev/null `
        tmp_previlege_users=`echo $tmp_previlege_users | /usr/bin/sed  "s/,/ /g"  2> /dev/null `
        tmp_previlege_users=`/usr/bin/echo $tmp_previlege_users 2> /dev/null`
        [ -z "$tmp_previlege_users" ] && tmp_previlege_users="None"
        format_display "$tmp_previlege_users"
        echolog '$2 $3: $4' "esdomadm" "\r\t\t\t\t" "$tmp_display_string"
       
        tmp_previlege_users=`/usr/bin/grep esops /etc/group | /usr/bin/cut -f4 -d: 2> /dev/null `
        tmp_previlege_users=`echo $tmp_previlege_users | /usr/bin/sed  "s/,/ /g"  2> /dev/null `
        tmp_previlege_users=`/usr/bin/echo $tmp_previlege_users 2> /dev/null `
        [ -z "$tmp_previlege_users" ] && tmp_previlege_users="None"
        format_display "$tmp_previlege_users"
        echolog '$2 $3: $4' "esops" "\r\t\t\t\t" "$tmp_display_string"
        echolog ''
        format_display "$USERLIST"
        echolog 'ALL USERS$2: $3' "\r\t\t\t\t" "$tmp_display_string"
        echolog '-------------------------------------------------------------------------------'
 
        echolog ''
        check_configured_user "${USER}"
    fi

    # Removed as requirement for validating configd dropped
    #check_proper_configd
    
    # SunMC server reachable
    if [ ! -z "$SERVER" ] 
    then
        echolog ''
        is_local_host "$SERVER"
        if [ $? -eq 0 ]
        then
            echolog 'server is local host'
        else
            echolog 'Checking connectivity to server...'
            check_ping_connectivity "$SERVER_NAME"
        fi
    fi
   
    
    if [ -n "$USER" -a"$JAVA_FOUND" = "Y" ]
    then

        echolog ''
        echolog 'Checking server login for $2...' "$USER"

        JAVAQUERYFILE=/tmp/javaqueryfile.$$
        SERVER_LOGIN=1
        do_remote_check "CheckLogin"
        /usr/bin/cat $JAVAQUERYFILE | /usr/bin/grep "Server login check OK" >/dev/null 2>&1
        if [ $? -eq 0 ] ; then
            echolog 'Server login check sucessfull.'
            SERVER_LOGIN=1
        else
            echolog 'Server login check failed.'
            echolog 'Ensure that server is running and user $2 is valid Sun Management Center user.' "$USER"
            SERVER_LOGIN=0
        fi
        /usr/bin/rm -f  "$JAVAQUERYFILE"

    fi

    if [ "$A_OPT" = "Y" ]
    then
        if [ -z "$AGENTPORT" ]
        then
            AGENTPORT=161
        fi
        echolog ''
        echolog '-------------------------------------------------------------------------------'
        echolog 'Checking connecitivity to agent host mentioned with -a command line option'
        echolog '-------------------------------------------------------------------------------'
        check_ping_connectivity "$AGENTHOST"
        if [ $? -eq 0 ] ; then
            echolog ' '
            echolog 'Checking if agent is running on $2:$3' $AGENTHOST $AGENTPORT
            check_sunmc_agent_connectivity "$AGENTHOST" "$AGENTPORT"

             # SunMC agent version
             if [ "$GET_AGENT_VERSION" = "Y" ]
             then
                 echolog ''
                 echolog 'Checking version of agent running on $2:$3.' $AGENTHOST $AGENTPORT
                 get_agent_version $AGENTHOST $AGENTPORT
             fi

             if [ "$GET_MODULES" = "Y" ]
             then
                 echolog ''
                 GOT_MODULES="N"
                 if [ "$no_server" = 0 -o "$no_console" = 0 ]
                 then
                     get_loaded_modules_using_client_api $AGENTHOST $AGENTPORT
                     if [ $? -eq 0 ]
                     then
                         GOT_MODULES="Y"
                     fi
                 fi
                 if [ "$GOT_MODULES" = "N" -a "$no_agent" = 0 ]
                 then
                     get_loaded_modules_using_snmp $AGENTHOST $AGENTPORT
                 fi
             fi

             if [ "$GET_ALARMS" = "Y" ]
             then
                 echolog ''
                 check_client_alarms_api
             fi
        fi
    fi

    
    #
    #  Check : Gather agent list using clientAPI
    #
    if [ "$GET_AGENT_LIST" = "Y" ] && [ "$JAVA_FOUND" = "Y" ]
    then
        if [ "$SERVER_LOGIN" = "1" ]
        then
            get_agents_in_context
        else
            echolog ''
            echolog 'Gathering the list of agents in server context skipped due to login failure'
        fi
    fi
    
    echolog '-------------------------------------------------------------------------------'
    check_webserver_connectivity

}


process_options_ValTool() {
    GET_ALARMS="N"
    GET_AGENT_LIST="N"
    S_OPT="N"
    while getopts u:p:a:b:o:s:r:vhcdlm OPT
    do
        case $OPT in
            u)
                # SunMC username
                USER="$OPTARG"
                ;;
            p)
                # password for SunMC username
                PASSWORD="$OPTARG"
                ;;
            a)
                # name or IP of SunMC agenthost
                AGENTHOST="$OPTARG"
                A_OPT="Y"
                ;;
            b)
                # port of SunMC agenthost
                AGENTPORT="$OPTARG"
                ;;
            c)
                # flag for whether to get list of agent in Server context
                GET_AGENT_LIST="Y"
                DO_ONLY_ONE_CHECK=1
                ;;
            d)
                # get version of agent
                GET_AGENT_VERSION="Y"
                DO_ONLY_ONE_CHECK=1
                ;;
            l)
                # unsupported option - get alarms for agent given with -a option
                GET_ALARMS="Y"
                ;;
            m)
                # unsupported option - get modules list for agent given with -a option
                GET_MODULES="Y"
                ;;
            o)
                # output file specified by user for log
                LOGFILE="$OPTARG"
                OUTFILE="$OPTARG"
                ;;
            s)
                # hostname or IP of SunMC server
                SERVER_NAME="$OPTARG"
                S_OPT="Y"
                ;;
            r)
                # RMI port of SunMC server, default 2099
                PORT="$OPTARG"
                ;;
            v)
                # flag for whether to show details on terminal
                VERBOSE=y
                ;;
            h)
                usage
                exit 0
                ;;
            *)
                usage
                exit 9
                ;;
        esac
    done

    VERBOSE=y
    get_passwd
}


show_config () {

    echolog ''
    UNAMEM=`/usr/bin/uname -m`
    #MEMSIZE=`/usr/platform/${UNAMEM}/sbin/prtdiag | /usr/bin/grep '^Memory' |/usr/bin/awk -F: '{print $2}`
    MEMSIZE=`/usr/sbin/prtconf | grep "^Memory size: " | /usr/bin/cut -d: -f2`
    NCPU=`/usr/bin/uname -X | /usr/bin/grep '^NumCPU' | /usr/bin/awk -F= '{print $2}'`
    HW=`/usr/bin/uname -i`
    HOSTNAME="`/usr/bin/hostname`"
    OS="`/usr/bin/uname -s` `/usr/bin/uname -r`"
    VERSION="3.5 Update 1"

    if [ "$no_server" = "0" -o "$no_console" = "0" ] ; then
        checkJavaOK
        ret=$?
        if [ $ret -eq 0 ] ; then
            JAVA_FOUND=Y
            JAVA="$SYMON_JAVAHOME/bin/java"
            CLASSPATH=$BASEDIR/classes/esmsg.jar:$BASEDIR/classes/jaxp1.1.3/crimson.jar:$BASEDIR/classes/jaxp1.1.3/xalan.jar:$BASEDIR/classes:$BASEDIR/classes/esclt.jar:$BASEDIR/classes/escom.jar:$BASEDIR/classes/essrv.jar:$BASEDIR/classes/esjrm.jar:.
        else
            echolog 'Skipping java dependent probes...'
            echolog ''
            echolog '-------------------------------------------------------------------------------'
            JAVA_FOUND=N
        fi
    fi
    
    echolog 'Validation Tool Version $2: $3' "\r\t\t\t\t" "${VERSION}"
    echolog 'Host name $2: $3' "\r\t\t\t\t" "$HOSTNAME"
    echolog 'Number of CPUs $2: $3' "\r\t\t\t\t" "$NCPU"
    echolog 'Platform $2: $3' "\r\t\t\t\t" "${HW}"
    echolog 'Operting System $2: $3' "\r\t\t\t\t" "$OS"
    echolog 'Memory size $2: $3' "\r\t\t\t\t" "${MEMSIZE}"
    
    SWAP=`/usr/bin/env LANG=C LC_MESSAGES=C LC_ALL=C /usr/sbin/swap -s 2> /dev/null`
    SWAP=`/usr/bin/echo $SWAP | /usr/bin/cut -d"=" -f2 | /usr/bin/cut -f1 `
    echolog 'Swap space $2: $3' "\r\t\t\t\t" "$SWAP" 
    
    [ ! -z "$JAVA_VERSION" ] && echolog 'JAVA VERSION $2: $3' "\r\t\t\t\t" "$JAVA_VERSION"
    
    echolog '-------------------------------------------------------------------------------'
    echolog ''

}


display_diskspace_details() {
    
    [ "$DO_ONLY_ONE_CHECK" = "1" ] && return
    
    echolog ''
    echolog ''
    echolog 'Sun Management Center disk-space consumption:'
    echolog '-------------------------------------------------------------------------------'
    echolog 'PRODUCT$2APPROXIMATE DISK SPACE CONSUMED' "\r\t\t\t\t"   
    echolog '-------------------------------------------------------------------------------'
    tmp_l_all_registry_packages=""
    total_sunmc_disk_space=0
    for each_product in `$CMD_ECHO "$L_INSTALLED_PRODUCTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        tmp_prod_name=`get_product_names "$each_product"`     
        tmp_prod_name=`/usr/bin/echo $tmp_prod_name | /usr/bin/cut -c 1-31 `
        tmp_l_components=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component" "key" 2> /dev/null `
        tmp_l_packages=""
        for each_component in `/usr/bin/echo "$tmp_l_components" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            tmp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package" "key" 2> /dev/null `
            [ $? -gt 0 ] && echolog 'Registry read error.' && return 1
            tmp_l_packages="$tmp_l_packages $tmp_list"
            tmp_l_packages=`/usr/bin/echo $tmp_l_packages | /usr/bin/sed "s/,/ /g" 2> /dev/null `
        done
        
        # Get oracle packages in case of server layer 
        #
        if [ "$no_server" = "0" -a "$each_product" = "PRODUCT.PE" ]; then
           tmp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_package" "key" 2> /dev/null `
           tmp_l_packages="$tmp_l_packages $tmp_list"
           tmp_l_packages=`/usr/bin/echo $tmp_l_packages | /usr/bin/sed "s/,/ /g" 2> /dev/null `
        fi
      
        # Make list unique - No package name should be repeate :tmp_l_ok_packages
        #
        tmp_l_packages=`/usr/bin/echo $tmp_l_packages | /usr/bin/sed "s/ /,/g" `
        tmp_l_packages="$tmp_l_packages,@"
        for each_package in `$CMD_ECHO "$tmp_l_packages" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            tmp_l_packages=`/usr/bin/echo $tmp_l_packages | /usr/bin/sed "s/$each_package,/###/" `       
            tmp_l_packages=`/usr/bin/echo $tmp_l_packages | /usr/bin/sed "s/$each_package,//g" `       
            tmp_l_packages=`/usr/bin/echo $tmp_l_packages | /usr/bin/sed "s/###/$each_package,/" `
        done
        tmp_l_packages=`/usr/bin/echo $tmp_l_packages | /usr/bin/sed "s/@//" `
 
        # For each package, calculate disk space and add it to total
        #
        tmp_disk_space=0
        for each_package in `$CMD_ECHO "$tmp_l_packages" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
             /usr/bin/pkginfo -qi $each_package 1>/dev/null 2>&1
             if [ $? -eq 0 ] ; then
                tmp_block_line=`/usr/bin/env LANG=C LC_MESSAGES=C LC_ALL=C /usr/bin/pkginfo -l $each_package | /usr/bin/grep -w "blocks" 2> /dev/null`
                tmp_block=`/usr/bin/echo $tmp_block_line | /usr/bin/cut -f1 -d' ' 2> /dev/null`
                /usr/bin/expr $tmp_block + 1 1>/dev/null 2>&1
                if [ $? -eq 0 ] ; then
                   tmp_disk_space=`/usr/bin/expr $tmp_disk_space + $tmp_block 2> /dev/null `
                else
                   tmp_disk_space=0
                fi
             fi
        done
        tmp_disk_space=`/usr/bin/expr $tmp_disk_space \/ 2 2> /dev/null `
        /usr/bin/expr $tmp_disk_space + 0 1>/dev/null 2>&1
        [ $? -ne 0 ] && tmp_disk_space=0

        if [ "$tmp_disk_space" -gt 0 ] ; then
           #tmp_display_no=":`/usr/bin/printf "%20d" "$tmp_disk_space" 2> /dev/null  `"
           echolog '$2 $3: $4 kB' "$tmp_prod_name" "\r\t\t\t\t" "$tmp_disk_space"
           total_sunmc_disk_space=`/usr/bin/expr $tmp_disk_space + $total_sunmc_disk_space 2> /dev/null `
        else
           echolog '$2 $3: ??' "$tmp_prod_name" "\r\t\t\t\t" 
        fi
    done

    echolog '$2 $3' "\r\t\t\t\t" "---------------"
    echolog 'TOTAL$2: $3 kB' "\r\t\t\t\t" "$total_sunmc_disk_space"
    echolog ''
    /usr/bin/pkginfo -qi SUNWestbl 1>/dev/null 2>&1
    if [ $? -eq 0 ] ; then
       pkgestbl_loc=`/usr/bin/pkginfo -r SUNWestbl 2> /dev/null`
       if [ ! -z "$pkgestbl_loc" ] ; then
          echolog 'Database is located at$2: $3' "\r\t\t\t\t" "$pkgestbl_loc"
          getAvailableSpace "$pkgestbl_loc"
          echolog 'Free space available on this partition is : $2 kB' "$AVAILABLE_SPACE"
       fi
    fi
    
   echolog '-------------------------------------------------------------------------------'

    echolog ''
#    getAvailableSpace "/"
#    echolog 'DISK SPACE ON /$2:$3' "\r\t\t\t\t" "$AVAILABLE_SPACE"
#    getAvailableSpace "/etc"
#    echolog 'DISK SPACE ON /etc$2:$3' "\r\t\t\t\t" "$AVAILABLE_SPACE"
#    getAvailableSpace "/tmp"
#    echolog 'DISK SPACE ON /tmp$2:$3' "\r\t\t\t\t" "$AVAILABLE_SPACE"

}


getAvailableSpace() {
    dir=$1
    if [ -d $dir ] ; then
        tmp_var_path=`addTrailSlashSUNWymon "$dir"`
        [ -d "$tmp_var_path" ] && dir="$tmp_var_path"        
    
        df_line=`$CMD_DF -k "$dir" | $CMD_TAIL -1`
        AVAILABLE_SPACE=`$CMD_ECHO "$df_line" | $CMD_AWK '{ print $4 }'`
        # Double the number reported by df -k to get 512-byte blocks to get
        # the same units as pkgmap
        
    else
        AVAILABLE_SPACE=0
    fi
unset dir tmp_var_path df_line
}


# $1 - directory
# echo's the above directory with a trailslash
addTrailSlashSUNWymon() {
    dir=$1
    trailslash=`$CMD_ECHO "$dir" | $CMD_GREP -i '/$' | $CMD_WC -l`
    if [ $trailslash = 0 ] ; then
        dir="${dir}/SUNWsymon"
    else
        dir="${dir}SUNWsymon"
    fi
    $CMD_ECHO "$dir"
    unset trailslash dir
    
}

    
terminate() {
    /usr/bin/stty echo
    /usr/bin/echo "Interrupted"
    exit 1
}


log () {
    DATE=`/usr/bin/date '+%m/%d/%y %H:%M:%S'`
    /usr/bin/echo "$1" >> $LOGFILE
    #/usr/bin/echo "${DATE} | $1" >> $LOGFILE
    if [ ! -z "$VERBOSE" ]
    then
        /usr/bin/echo "$1"
        #/usr/bin/echo "${DATE} | $1"
    fi
}


check_sunmc_license () {
    license_file="${VARDIR}/.license"
    if [ -f "$license_file" ] 
    then
        license=`/usr/bin/grep -v "^#" $license_file `
        if [ -z "$license" ] 
        then
	    log "\t[FAIL] License Not Available"
            return 1
        else
	    LICENSE=TRUE
	    log "\t[PASS] License Available"
        fi
    else
	log "\t[FAIL] License Not Available"
        return 1
    fi
    return 0
}


check_premier_packages () {
    premier_packages="SUNWessvc SUNWesweb SUNWesasc SUNWesmcp SUNWescli SUNWescix SUNWescdv"
    installed=true
    for each_package in $premier_packages
    do
	/usr/bin/pkginfo -qi $each_package
	if [ $? -eq 1 ] ; then
	    log '    $2 not installed' "$each_package"
            installed=false
	fi
    done
    if [ "$installed" = "false" ] ; then
        log "\t[FAIL] Premier packages not installed correctly"
        return 1
    else
	PREMIER_PACKAGES=TRUE
        log "\t[PASS] Premier packages installed correctly"
    fi

    return 0
}


get_passwd() {
    if [ ! -z "${USER}" -a  -z "${PASSWORD}" ]; then
       PWDONE=0
       while [ ${PWDONE} = 0 ]
       do
          /usr/bin/echo "Enter password for Sun Management Center user ${USER}: \c"
          /usr/bin/stty -echo
          read PW1
        
          /usr/bin/echo ""
  
          /usr/bin/echo "Enter password again: \c"
          read PW2
         
          /usr/bin/stty echo
          /usr/bin/echo ""
     
          if [ "${PW1}" = "${PW2}" ]; then
              PWDONE=1
              PASSWORD=$PW1
          else
              /usr/bin/echo "Passwords do not match. Try again."
          fi 
       done
    fi
}


check_configured_user () {
    USTATUS=0
    ESUSERS="${VARDIR}/esusers"
    
    [ -z "$1" ] && return 0
    
    [ ! -f "$ESUSERS" ] && return 0
    [ "$no_server" = "1" ] && return 0

    /usr/bin/getent passwd "$1" 1>/dev/null 2>&1
    if [ $? -ne 0 ]; then
       echolog 'User $2 not found in /etc/passwd. ' "${USER}"
       USTATUS=1
    fi
  
    /usr/bin/grep "^$1" ${ESUSERS} 1>/dev/null 2>&1
    if [ $? -eq 0 ]; then
       echolog 'User $2 is configured as a Sun Management Center user.' "${USER}"
    else
       echolog 'User $2 is not configured in $3.' "${USER}" "${ESUSERS}"
       USTATUS=1
    fi
    return $USTATUS
}


check_webserver_packages () {

    #web_packages="SUNWesweb"
    web_packages="SUNWtcatu"
    installed=true
    for each_package in $web_packages
    do
	/usr/bin/pkginfo -qi $each_package
	if [ $? -eq 1 ] ; then
	    echolog '$2 not installed.' "$each_package"
            installed=false
	fi
    done
    if [ "$installed" = "false" ] ; then
        echolog 'Web server package is not installed correctly.'
        return 1
    else
	WEBSERVER_PACKAGES=TRUE
        echolog 'Web server package is installed correctly.'
    fi

    return 0
}


check_webserver_connectivity () {
    
    [ "$no_server" = "1" ] && return 0
    [ "$server_setup" != "1" ] && return 0 

    echolog ''
    echolog '-------------------------------------------------------------------------------'
   
    check_webserver_packages
    
    if [ "$WEBSERVER_PACKAGES" = "FALSE" ] ; then
        return 1
    fi
    httpoutfile="/tmp/httpoutfile$$"
    basedir=`/usr/bin/pkginfo -r SUNWescom` 
    httptest=$basedir/SUNWsymon/base/bin/httprequest
    if [ ! -x "$httptest" ]
    then
        echolog 'Error finding http executable.'
        return 2
    fi
    $httptest -p ${WEBPORT} -s ${SERVER} -o ${httpoutfile} -u "GET / HTTP/1.0" 1>/dev/null 2>&1
    /usr/bin/grep -v '^HTTP 1.[01] 200 OK' ${httpoutfile} 1>/dev/null 2>&1
    if [ $? -eq 0 ] 
    then
	WEBSERVER_CONNECTIVITY=TRUE
        echolog 'Web Server is up and responding.'
        /usr/bin/rm -f $httpoutfile

        check_servlet_connectivity
    else
        echolog 'Web Server is not responding. Can not verify connectivity check.' 
        /usr/bin/rm -f $httpoutfile
    fi 
    
    echolog '-------------------------------------------------------------------------------'
   
}


check_servlet_connectivity () {
   
    [ "$no_server" = "1" ] && return 0
 
    httpoutfile="/tmp/httpoutfile$$"

    basedir=`/usr/bin/pkginfo -r SUNWescom` 
    httptest=$basedir/SUNWsymon/base/bin/httprequest
    $httptest -p ${WEBPORT} -s ${SERVER} -o ${httpoutfile} -u "GET /loginpage HTTP/1.0"
    /usr/bin/grep -v '^HTTP 1.[01] 200 OK' ${httpoutfile} 1>/dev/null 2>&1
    if [ $? -eq 0 ] ; then
	SERVELET_CONNECTIVITY=TRUE
        echolog 'Web Server servlet engine is up and responding.'
        /usr/bin/rm -f $httpoutfile
	return 0
    else
        echolog 'Web Server servlet engine is not responding.'
        /usr/bin/rm -f $httpoutfile
        return 1
    fi 
    return 0
}



# The function is to invoke client API calls 
# Services provided are 
#    CheckLogin
#    ListAgents
#    ListModules
#    ListAlarms
# Returns status in file : $JAVAQUERYFILE
#
do_remote_check () {

    /usr/bin/pkginfo -qi SUNWesclt  > /dev/null 2>&1
    if [ $? -ne 0 ] ; then
        echolog 'SUNWesclt package is missing. Can not perform remote checks to get-  $2.' "$1"
        return 1        
    fi

    [ "$SERVER_LOGIN" = 0 ] && return 1        

    [ -z "$JAVAQUERYFILE" ] && JAVAQUERYFILE=/tmp/javaqueryfile.$$
    [ -z "$AGENTHOST" ] && AGENTHOST="$LOCALHOST"
    [ -z "$AGENTPORT" ] && AGENTPORT=161
    [ -z "$SERVER" ] && echolog 'Server name is not specified. Use -s option.' && return 1
    
    [ -z "$USER" ] && echolog 'User name is not specified. Use -u option.' && return 1
    
    $JAVA -classpath $CLASSPATH com.sun.symon.tools.validationtool.RemoteChecks $SERVER $PORT $AGENTHOST $AGENTPORT $USER $PASSWORD "$1" 2>/dev/null > $JAVAQUERYFILE
    return 0
}

# Get information about active alarms
#
check_client_alarms_api () {
     echolog 'Gathering list of alarms on agenthost $2...' "$AGENTHOST"
       
     JAVAQUERYFILE=/tmp/javaqueryfile.$$
     
     do_remote_check "ListAlarms"
     if [ $? -eq 0 ]; then
        /usr/bin/cat $JAVAQUERYFILE | /usr/bin/grep "Severity:" >/dev/null 2>&1
        if [ $? -eq 0 ] ; then
           echolog '-------------------------------------------------------------------------------'
           echolog 'Found following alarms on agent host $2' "$AGENTHOST"
           echolog '-------------------------------------------------------------------------------'
           /usr/bin/cat $JAVAQUERYFILE | /usr/bin/grep "Severity:" 
           /usr/bin/rm -f  "$JAVAQUERYFILE"
           return 0
        else
           echolog 'Alarms list on agenthost $2 is empty OR not available.' "$AGENTHOST"
           /usr/bin/rm -f  "$JAVAQUERYFILE"
           return 1
        fi
     fi  

}


show_sunmc_version_patch () {
    sunmc_version=`/usr/bin/pkgparam SUNWescom SUNW_PRODVERS`
    echolog "Installed Sun Management Center version = $sunmc_version"

    sunmc_packages_installed=`/usr/bin/pkginfo -c symon | /usr/bin/nawk ' {print $2}' `
    patches_installed=`/usr/bin/showrev -p | /usr/bin/nawk ' {print $2}' `
    sunmc_patches_installed=""
    for each_patch in $patches_installed
    do
        packages=`/usr/bin/showrev -p | /usr/bin/grep "Patch: $each_patch" | /usr/bin/cut -d : -f 6`
        packages=`echo $packages | /usr/bin/sed -e 's/,//g'`
        for each_package in $packages
        do
            echo "$sunmc_packages_installed" | /usr/bin/grep -w "$each_package" > /dev/null 2>&1
            if [ $? -eq 0 ] ; then
                if [ -z "$sunmc_patches_installed" ] ; then
                    sunmc_patches_installed="$each_patch"
                else
                    sunmc_patches_installed="$sunmc_patches_installed $each_patch"
                fi
                break
            fi
        done
    done
    log "\tSun Management Center patches installed = $sunmc_patches_installed"
    return 0
}


get_loaded_modules_using_snmp () {
    module_name_file=/tmp/module_name$$
    module_count_file=/tmp/module_count$$
    /usr/bin/echo "\c" > $module_name_file
    /usr/bin/echo "\c" > $module_count_file
    $UTIL_DIR/snmpget -h $1 -p $2 -c public -t 10 1.3.6.1.4.1.42.2.12.2.1.2.3.1.1.7 > $module_name_file 2>&1
    $UTIL_DIR/snmpget -h $1 -p $2 -c public -t 10 1.3.6.1.4.1.42.2.12.2.1.2.3.1.1.6 > $module_count_file 2>&1
    error_line=`/usr/bin/cat $module_name_file`
    if [ "$error_line" = "Request Timed Out" ] 
    then
        echolog 'SNMP request timed out while geting all module names'
        /usr/bin/rm -f $module_name_file $module_count_file
        return 1
    fi
    error_line=`/usr/bin/cat $module_count_file`
    if [ "$error_line" = "Request Timed Out" ] 
    then
        echolog 'SNMP request timed out while geting all module status'
        /usr/bin/rm -f $module_name_file $module_count_file
        return 1
    fi
    error_code=`/usr/bin/cat $module_name_file | /usr/bin/grep "^Error:" | /usr/bin/nawk ' { print $2 }'`
    if [ "$error_code" != "noError" ] 
    then
        echolog 'Could not get module names using snmp.'
        /usr/bin/rm -f $module_name_file $module_count_file
        return 1
    fi
    error_code=`/usr/bin/cat $module_count_file | /usr/bin/grep "^Error:" | /usr/bin/nawk ' { print $2 }'`
    if [ "$error_code" != "noError" ] 
    then
        echolog 'Could not get module status using snmp.'
        /usr/bin/rm -f $module_name_file $module_count_file
        return 1
    fi
    module_names_list=`/usr/bin/cat $module_name_file | /usr/bin/grep "^Value:" | /usr/bin/cut -d '"' -f 2`
    module_status_list=`/usr/bin/cat $module_count_file | /usr/bin/grep "^Value:" | /usr/bin/cut -d '"' -f 2`
    loaded_modules=""
    i=0
    for each_module in $module_names_list
    do
        i=`/usr/bin/expr $i + 1`
        module_status=`echo $module_status_list | /usr/bin/cut -d " " -f $i `
        if [ $module_status -ne 0 ] ; then
            if [ -z "$loaded_modules" ] ; then
                loaded_modules="$each_module"
            else
                loaded_modules="$loaded_modules $each_module"
            fi
        fi
    done
    echolog 'Loaded modules ='
    for M in $loaded_modules
    do
       echolog '$2 $3' "\t" $M
    done
    /usr/bin/rm -f $module_name_file $module_count_file
    
    return 0
}


get_loaded_modules_using_client_api () {

     echolog 'Gathering list of loaded modules on agent $2...' "$AGENTHOST"
    
     JAVAQUERYFILE=/tmp/javaqueryfile.$$
     do_remote_check "ListModules"
     [ $? -ne 0 ] && return 1
     
     /usr/bin/cat $JAVAQUERYFILE | /usr/bin/grep "Module:" >/dev/null 2>&1
     if [ $? -eq 0 ] ; then

        echolog '-------------------------------------------------------------------------------'
        echolog 'Following Modules are loaded on agent host $2' "$AGENTHOST"
        echolog '-------------------------------------------------------------------------------'
     
           /usr/bin/cat $JAVAQUERYFILE | /usr/bin/grep "Module:" 2>/dev/null
           /usr/bin/rm -f  "$JAVAQUERYFILE"
           return 0

     else
           echolog 'Module list for agenthost $2 is empty or not available.' 
           /usr/bin/rm -f  "$JAVAQUERYFILE"
           return 1
     fi
}


check_ping_connectivity () {
    /usr/sbin/ping "$1" > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
        HOST_ALIVE=TRUE
        echolog 'Connection to host $2 is alive. [ICMP ping]' "$1"
    else
        echolog 'Connection to host $2 is not reachable. [ICMP ping]' "$1"
        return 1
    fi
    return 0
}


check_sunmc_agent_connectivity () {
    if [ ! -x "$UTIL_DIR/snmpget" ] ; then
       echolog 'SNMP utilities are not available. Skipping SNMP dependent checks...'
       return 1
    fi
    
    error_line=`$UTIL_DIR/snmpget -h $1 -p $2 -t 10 1.3.6.1.4.1.42.2.12.2.1.2.1.3.0 2> /dev/null | /usr/bin/grep "Error:" `
    error_code=`/usr/bin/echo $error_line | /usr/bin/cut -d : -f 2`
    error_code=`/usr/bin/echo $error_code`
    if [ "$error_code" = "noError" ] ; then
	SUNMC_AGENT=TRUE
        echolog 'SNMP communication okay with Sun Management Center agent running on $2:$3.' $1 $2
    else
        echolog 'SNMP communication failed with Sun Management Center agent running on $2:$3.' $1 $2
        return 1
    fi
    return 0
}


get_util_dir () {
    UTIL_DIR="$BASEDIR/util/bin/"
    return 0
}


get_http_port () {
    
    basedir=`/usr/bin/pkginfo -r SUNWescom`
    webcfgfile="$basedir/SUNWsymon/netscape/https-localhost/config/magnus.conf"
    WEBPORT=""
    if [ -f "$webcfgfile" ]
    then
    	WEBPORT=`/usr/bin/grep "^Port" $webcfgfile | /usr/bin/nawk ' { print $2 }' `
    else
        echolog 'netscape configuration file \"$webcfgfile\" missing ...'
    fi

    #echo "while getting port $WEBPORT"
    if [ -z "$WEBPORT" ] ; then
        WEBPORT=80
    fi
}


convert_host_to_address () {

    if [ ! -z "$SERVER_NAME" ]
    then
        SERVER=`/usr/sbin/ping -s $SERVER_NAME | /usr/bin/head -2 | /usr/bin/tail -1 | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`   
    fi
}


is_local_host() {

    HOST_NAME=$1
    LOCALHOST=`/usr/bin/hostname`

    HOST_IP=`/usr/sbin/ping -s $HOST_NAME | /usr/bin/head -2 | /usr/bin/tail -1 | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`

    LOCALHOST_IP=`/usr/sbin/ping -s $LOCALHOST | /usr/bin/head -2 | /usr/bin/tail -1 | /usr/bin/cut -d'(' -f2 | /usr/bin/cut -d')' -f1`

    if [ "$LOCALHOST_IP" = "$HOST_IP" ]
    then
        #echo host $HOST_NAME is local
        return 0
    else
        #echo host $HOST_NAME is not local
        return 1
    fi

}


get_agents_in_context() {
    
    echolog ''
    echolog 'Gathering list of agenthosts for Sun Management Center server $2...' "$SERVER"

    JAVAQUERYFILE=/tmp/javaqueryfile.$$
    do_remote_check "ListAgents"
    if [ $? -eq 0 ] ; then
        AGENT_LIST=""
        [ -r "$JAVAQUERYFILE" ] &&  AGENT_LIST=`/usr/bin/cat $JAVAQUERYFILE `

        echolog '-------------------------------------------------------------------------------'
        echolog 'AGENT $2 ICMP PING STATUS FROM THIS HOST' "\r\t\t\t\t\t"
        echolog '-------------------------------------------------------------------------------'
        I=1
        for AGENT in ${AGENT_LIST} 
        do
           IP=`/usr/bin/echo $AGENT | /usr/bin/awk -F: '{print $1}'`
           HENTRY=`/usr/bin/getent hosts $IP 2>/dev/null`
           if [ $? -ne 0 ]; then
              HNAME=
           else
              HNAME="`/usr/bin/echo $HENTRY | /usr/bin/awk '{print $2}'`"
           fi 
           /usr/sbin/ping "$IP" > /dev/null 2>&1
           if [ $? -eq 0 ] ; then
               echolog '$I. ${AGENT} ${HNAME} $2'  "\r\t\t\t\t\t\tOK"
           else
               echolog '$I. ${AGENT} ${HNAME} $2'  "\r\t\t\t\t\t\tFAILED"
           fi
         
           I=`/usr/bin/expr $I + 1`
        done
   
    else
        AGENT_LIST=""
        echolog 'Error while gathering agent list'
    fi
    /usr/bin/rm -f "$JAVAQUERYFILE"

}


usage () {
    eval /usr/bin/echo "\"`/usr/bin/gettext 'Usage: $PROGNAME [-s <server> [-r <serverport>][-u <username> [-p <password>]]][-a agenthost [-b agentport] [-d]] [-c] [-o <outfile>]\n'`\""

   /usr/bin/gettext '   -s server      Sun Management Center server name.\n' 
   /usr/bin/gettext '               If not specified, the current host will be used.\n'
   /usr/bin/gettext '   -r serverport  Sun Management Center RMI port number.\n' 
   /usr/bin/gettext '               If not specified, the 2099 will be used.\n'
   /usr/bin/gettext '   -u username    user name used to connect with Sun Management Center server.\n'
   /usr/bin/gettext '               This is mendatory parameter for login checks.\n'
   /usr/bin/gettext '   -p password    Password for username.  If not specified and -u is selected,\n' 
   /usr/bin/gettext '               this will be obtained via interactive prompting.\n'
   /usr/bin/gettext '   -a agenthost   To check connectivity with this agenthost.\n'
   /usr/bin/gettext '   -b agentport   SNMP port number associated with agenthost.\n'
   /usr/bin/gettext '   -c             Show all the agents in the context of Sun Management Center\n' 
   /usr/bin/gettext '               server specified with -s option.\n'
   /usr/bin/gettext '   -d             Show version of agent on agenthost\n'
   /usr/bin/gettext '   -o outfile     The output of the tool will be stored in outfile.\n' 
   /usr/bin/gettext '               Outfile should be absolute file path.\n' 
   /usr/bin/gettext '               Default will be an arbitrary filename in /tmp\n'

#   -v             Verbose output mode.

}


#
# This function can be invoked on any sunmc version.
# Registry validation and product dependacy is only 
# applicable to sunmc 3.5
#
# The function will display four tables.
# TABLE 1. Installation status which will tabulate sunmc addons
#          installed, there installation status and packages status
#          corresponding to each of the product.
# TABLE 2. Tabulation of product dependacies and versions of sunmc 
#          addons ( 3.5 only )
#
# TABLE 3. Tabulation of sunmc patches
# TABLE 4. Tabulation of Registry validation
# TABLE 5. Tabulation of ports used by sunmc
#
validate_installation_details () {

    echolog ''
    if [ "$no_DE" = "0" ] ; then
        echolog 'Sun Management Center Developer Environment Installation.'     
    else
       echolog 'Sun Management Center Production Environment Installation.' 
       [ "$no_HA" = "0" ] && echolog 'Highly Available Server is installed.'
    fi
    echolog ''
    # Display what layers installed
    #    
    
    #tmp_installed_layers=`/usr/bin/echo "$L_BASE_INSTALLED_LAYERS" | /usr/bin/tr "[:upper:]" "[:lower:]" 2> /dev/null `
    #tmp_installed_layers=`/usr/bin/echo "$tmp_installed_layers" | /usr/bin/sed "s/layer.//g" 2> /dev/null `
    
    tmp_installed_layers=`/usr/bin/echo "$L_BASE_INSTALLED_LAYERS" | /usr/bin/sed "s/LAYER.//g" 2> /dev/null `
    tmp_installed_layers=`/usr/bin/echo "$tmp_installed_layers" | /usr/bin/sed "s/ /, /g" 2> /dev/null `
    
    echolog 'Following layers are installed $2: $3' "\r\t\t\t\t" "$tmp_installed_layers"
    
    # Display installation localtion
    #    
    echolog 'Installation location $2: $3' "\r\t\t\t\t" "$BASEDIR"

    #
    # TABLE 1 : Productwise installation and setup details
    #
    display_table_product_packages
    
    #
    # TABLE 2 : Productwise dependancies and addon versions ( 4.x only )
    #
    display_table_product_dependacies
        
    #
    # TABLE 3 : Sun Management Center patches
    #
    display_table_patch_details

    #
    #
    display_diskspace_details

    # Display locales installed - in case of server only
    #
    display_locale_details
    
    # Display locales installed - in case of server only
    #
    display_upgrade_details

}

display_locale_details () {
  
    # Locale selection is applied to all layers now 
    #[ "$no_server" = "1" ] && return 0
    [ "$DO_ONLY_ONE_CHECK" = "1" ] && return

    echolog ''
    echolog '-------------------------------------------------------------------------------'
    tmp_existing_locales=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "locale" "key" 2>/dev/null`
    all_locale_list="C:English,zh_TW:Traditional#Chinese,zh:Simplified#Chinese,fr:French,de:German,it:Italian,ja:Japanese,ko:Korean,es:Spanish"
    tmp_existing_locales="${tmp_existing_locales},"  # Just add at end so that equals grep -w
    tmp_existing_locale_names=""
    for each_locale in `/usr/bin/echo "$all_locale_list" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
       tmp_locale_key=`/usr/bin/echo "$each_locale" | /usr/bin/cut -f1 -d":" 2> /dev/null`
       tmp_locale_name=`/usr/bin/echo "$each_locale" | /usr/bin/cut -f2 -d":" 2> /dev/null`
       
       /usr/bin/echo "$tmp_existing_locales" | /usr/bin/grep "${tmp_locale_key}," > /dev/null 2>&1
       if [ $? -eq 0 ]; then # found
          if [ -z "$tmp_existing_locale_names" ] ; then
             tmp_existing_locale_names="$tmp_locale_name"
          else
             tmp_existing_locale_names="$tmp_existing_locale_names,$tmp_locale_name"
          fi
       fi
    done
    tmp_existing_locale_names=`/usr/bin/echo $tmp_existing_locale_names | /usr/bin/sed "s/#/ /g" 2> /dev/null `
    echolog 'Following locales are installed$2: $3' "\r\t\t\t\t" "$tmp_existing_locale_names"
    echolog '-------------------------------------------------------------------------------'


}

display_upgrade_details() {
  
    [ "$DO_ONLY_ONE_CHECK" = "1" ] && return


    tmp_old_sunmc_version=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "oldversion" 2> /dev/null `
    tmp_old_sunmc_version=`/usr/bin/echo $tmp_old_sunmc_version 2> /dev/null `

    echolog ''
    echolog '-------------------------------------------------------------------------------'
    if [ ! -z "$tmp_old_sunmc_version" ] ; then
        echolog 'Present installation is upgrade from Sun Management Center version $2' "$tmp_old_sunmc_version"
    else
        echolog 'Information about upgrade from old versions is not available.'
    fi
    echolog '-------------------------------------------------------------------------------'
    
}


validate_setup_details () {

    display_table_sunmc_ports
    display_table_sunmc_server_hosts
    diaplay_table_SunMC_processes
    display_etc_system_status
}


display_etc_system_status () {
     
    [ "$no_server" = "1" ] && return 0

    echolog ''
    echolog '-------------------------------------------------------------------------------'
 
    # Check if node needs reboot
    #
    if [ -f $VAROPTDIR/cfg/lastboot ]; then
        /usr/bin/who -b > /tmp/temp_file
        /usr/bin/cmp temp_file $VAROPTDIR/cfg/lastboot >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            echolog 'Last run of es-setup modified Kernel parameters.'
            echolog 'System must be rebooted so that these changes become effective.'
            echolog ''
        fi  
    fi
    /usr/bin/rm -f /tmp/temp_file

    MEMSIZE=`/usr/sbin/prtconf | grep "Memory size: " | cut -f3 -d' '`
    if [ "$MEMSIZE" -lt "512" ]; then
        echolog 'A minimum of 512 MB RAM is required to run Sun Management Center.'
        echolog 'Current system has $2 MB RAM.' "$MEMSIZE"
        echolog ''
    fi
   
    # Check if /etc/system file is okay
    #
    if [ -r  "${BASEDIR}/lib/sbin/db-common.sh" ] ; then
       . ${BASEDIR}/lib/sbin/db-common.sh
       smcdb_check_system
       if [ "$SYSTEM_NEEDCHANGE" = "1" ] ; then
           echolog 'Configuration in /etc/system file needs to be changed.' 
           if [ "$server_setup" = "1" ] ; then
               echolog 'Run $2 and reboot the system.' "$BASEDIR/sbin/es-setup -F"
           else
               echolog 'Run $2 and reboot the system.' "$BASEDIR/sbin/es-setup"
           fi        
       else
           echolog '/etc/system file is configured correctly for Sun Management Center.' 
       fi
       
       /usr/bin/rm -f ${TEMP_FILE}
       /usr/bin/rm -f ${SYSTEM_TEMP}
    else
       echolog 'Can not source db-common.sh.'
    fi

   echolog '-------------------------------------------------------------------------------'
 
}


display_table_sunmc_ports () {

    [ "$server_setup" = "0" -a "$agent_setup" = "0" ] && return 1
    [ "$server_setup" = "1" ] && tmp_sunmc_components="agent trap event topology cfgserver cstservice metadata platform grouping rmi webserver_HTTP webserver_HTTPS"
    [ "$server_setup" = "0" -a "$agent_setup" = "1" ] && tmp_sunmc_components="agent trap event platform"
    
    if [ -f "${VARDIR}/platform-instances.dat" ] ; then
       list_of_instances=`$XGET ${VARDIR}/platform-instances.dat ControlBlock.instances   2> /dev/null`
       list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/,/ /g"  2> /dev/null`
    fi

    [ ! -z "$list_of_instances" ] && tmp_sunmc_components="$tmp_sunmc_components $list_of_instances"
    echolog ''
    echolog 'Sun Management Center Ports:'
    echolog '-------------------------------------------------------------------------------'
    echolog ' SUNMC COMPONENT $2 PORT_ID ' "\r\t\t\t\t" 
    echolog '-------------------------------------------------------------------------------'

    for each_component in $tmp_sunmc_components
    do
        find_present_port $each_component
        [ $? -ne 0 ] && port="?" && port_conflicts="Not Configured"
        this_port="$port"

        /usr/bin/expr $this_port + 1  1> /dev/null  2>&1 
        [ $? -ne 0 ] && this_port="?" 
        conflict_list=""
        for each_other_component in $tmp_sunmc_components
        do
            if [ "$each_other_component" != "$each_component" ] ; then
                find_present_port $each_other_component
                if [ $? -eq 0 -a ! -z "$port" ]; then
                    if [ "$this_port" = "$port" ] ; then # Add in conflict list
                        if [ -z "$conflict_list" ] ; then
                           conflict_list="$each_other_component"
                        else
                           conflict_list="$conflict_list,$each_other_component"
                        fi
                    fi
                fi
            fi
        done
       
        if [ ! -z "$conflict_list" ] ; then 
           echolog ' $2 service $3 $4 $5 Conflicts:$6' "$each_component" "\r\t\t\t\t" "$this_port" "\r\t\t\t\t\t" "$conflict_list"
        else
           echolog ' $2 service $3 $4  ' "$each_component" "\r\t\t\t\t" "$this_port"  
        fi
    done
    echolog ''
    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.'
        find_present_port "agent"
        [ "$port" = "161" ] && echolog 'Sun Management Center agent and SNMPDX are using conflicting port:$2.' "$port"
    fi
    
    echolog '-------------------------------------------------------------------------------'
    
}

# Checks for server host for a sunmc service in domain-config.x
# This check is mainly for components cconfigured in domain-config.x
#
display_table_sunmc_server_hosts () {

    [ "$server_setup" = "0" -a "$agent_setup" = "0" ] && return 1
    [ "$server_setup" = "1" ] && tmp_sunmc_components="agent trap event topology cfgserver cstservice metadata platform"
    [ "$server_setup" = "0" -a "$agent_setup" = "1" ] && tmp_sunmc_components="agent trap event platform"
    
    if [ -f "${VARDIR}/platform-instances.dat" ] ; then
       list_of_instances=`$XGET ${VARDIR}/platform-instances.dat ControlBlock.instances   2> /dev/null`
       list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/,/ /g"  2> /dev/null`
    fi

    [ ! -z "$list_of_instances" ] && tmp_sunmc_components="$tmp_sunmc_components $list_of_instances"
    echolog ''
    echolog 'Sun Management Center Server Hosts definitions in domain-config.x:'
    echolog '-------------------------------------------------------------------------------'
    echolog ' SUNMC COMPONENT $2 SERVER_HOST ' "\r\t\t\t\t" 
    echolog '-------------------------------------------------------------------------------'
    set_xput
    trap_server=`$XGET "$VARDIR/domain-config.x" "trap.trapServer"  2> /dev/null`
    event_server=`$XGET "$VARDIR/domain-config.x" "event.eventServer"  2> /dev/null`
    agent_server=`$XGET "$VARDIR/domain-config.x" "agent.agentServer"  2> /dev/null`

    host_conflict=0
    for each_component in $tmp_sunmc_components
    do
        host=`$XGET "$VARDIR/domain-config.x" "${each_component}.${each_component}Server"  2> /dev/null`
        host=`/usr/bin/echo $host  2> /dev/null `
        lower_host=`$CMD_ECHO $host | $CMD_TR '[:upper:]' '[:lower:]' `
        lower_HOSTNAME=`$CMD_ECHO $HOSTNAME | $CMD_TR '[:upper:]' '[:lower:]' `
        [ -z "$host" ] && host="?" 
        if [ "$no_server" = "1" ]; then
           [ "$each_component" != "trap" -a "$each_component" != "event" ]  && [ "$lower_host" != "$lower_HOSTNAME" ] && host_conflict=1 && host="$host \r\t\t\t\t\t\t\t#"
        else
           [ "$server_setup" = "1" ] && [ "$lower_host" != "$lower_HOSTNAME" ] && host_conflict=1 && host="$host \r\t\t\t\t\t\t\t#"
        fi
        echolog ' $2 service $3 $4  ' "$each_component" "\r\t\t\t\t" "$host"  
    done

    if [ "$no_server" = "1" ]; then 
       [ "$trap_server" = "$agent_server" ]  && host_conflict=1
       [ "$trap_server" != "$event_server" ]  && host_conflict=1
    fi

    echolog ''

    if [ "$host_conflict" = "1" ] ; then
       echolog 'WARNING: Sun Management Center server hosts are not configured correctly.'
       echolog 'Run $2 to configure Sun Management Center.' "$BASEDIR/sbin/es-setup -F"
    fi

    echolog ''
    echolog '-------------------------------------------------------------------------------'

}


find_SunMC_proc_status() {

    # Find if SunMC Java server running or not
    #
    SERVER_PID_FILE="$VAROPTDIR/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="$VAROPTDIR/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
    
    
    # Find if web server running or not
    #
    #/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="$VAROPTDIR/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_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
             [ $? -eq 0 ] && running_instances="$running_instances $each_instance"
          done
       fi
    fi 
   
    # 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

    # Find if database is running
    #
    /usr/bin/ps -eaf | /usr/bin/grep "SUNWsymon/oracle/product" | grep -v grep > /dev/null 2>&1
    database_start_error=$?

}

diaplay_table_SunMC_processes () {
   
    [ "$server_setup" = "0" -a "$agent_setup" = "0" ] && return 
    echolog ''
    echolog 'Sun Management Center Processes:'
    echolog '-------------------------------------------------------------------------------'
    echolog ' SUNMC SERVICE $2 STATUS ' "\r\t\t\t\t" 
    echolog '-------------------------------------------------------------------------------'

    find_SunMC_proc_status
    
    if [ "$server_setup" = "1" ] ; then
       if [ $SunMC_server_start_error -eq 0 ] ; then
          echolog 'Java Server $2 Running.' "\r\t\t\t\t"
       else
          echolog 'Java Server $2 Not Running.' "\r\t\t\t\t"
       fi
      
       if [ $database_start_error -eq 0 ] ; then
           echolog 'Database services $2 Running.' "\r\t\t\t\t"  
       else
           echolog 'Database services $2 Not Running.'  "\r\t\t\t\t"   
       fi
     
       if [ $grouping_service_start_error -eq 0 ] ; then
           echolog 'Grouping service $2 Running.' "\r\t\t\t\t"
       else
           echolog  'Grouping service $2 Not Running.' "\r\t\t\t\t"
       fi
       
       checkString "$started_processes" "event" 
       if [ $? -eq 0 ] ; then
          echolog 'Event-handler service $2 Running.' "\r\t\t\t\t"
       else
          echolog 'Event-handler service $2 Not Running.' "\r\t\t\t\t"
       fi

       checkString "$started_processes" "topology" 
       if [ $? -eq 0 ] ; then
           echolog 'Topology service $2 Running.' "\r\t\t\t\t"
       else
           echolog 'Topology service $2 Not Running.' "\r\t\t\t\t"
       fi
     
       checkString "$started_processes" "trap" 
       if [ $? -eq 0 ] ; then
           echolog 'Trap-handler service $2 Running.' "\r\t\t\t\t"
       else
             echolog 'Trap-handler service $2 Not Running.' "\r\t\t\t\t"
       fi

       checkString "$started_processes" "cfgserver" 
       if [ $? -eq 0 ] ; then
           echolog 'Configuration service $2 Running.' "\r\t\t\t\t"
       else
           echolog 'Configuration service $2 Not Running.' "\r\t\t\t\t"
       fi
       
       checkString "$started_processes" "cstservice" 
       if [ $? -eq 0 ] ; then
           echolog 'CST service  $2 Running.' "\r\t\t\t\t"
       else
           echolog 'CST service  $2 Not Running.' "\r\t\t\t\t"
       fi
       
       checkString "$started_processes" "metadata" 
       if [ $? -eq 0 ] ; then
          echolog 'Metadata Services $2 Running.' "\r\t\t\t\t"
       else
           echolog 'Metadata Services $2 Not Running.' "\r\t\t\t\t"
       fi

       # /usr/bin/ps -ef | grep -v "grep" | grep "DHWDS"   > /dev/null 2>&1
       if [ $HWDS_server_start_error -eq 0 ] ; then
          echolog 'Hardware service $2 Running.' "\r\t\t\t\t"
       else
          echolog 'Hardware service $2 Not Running.' "\r\t\t\t\t"
       fi

       if [ $web_server_start_error -eq 0 ] ; then
           echolog 'Web server  $2 Running.' "\r\t\t\t\t"
       else
           echolog 'Web server  $2 Not Running.' "\r\t\t\t\t"
       fi
    fi
    
    if [ "$agent_setup" = "1" ]; then
       checkString "$started_processes" "agent" 
       if [ $? -eq 0 ] ; then
          echolog 'Sun Management Center Agent  $2 Running.' "\r\t\t\t\t"    
       else
           echolog 'Sun Management Center Agent  $2 Not Running.' "\r\t\t\t\t"    
       fi
       
       checkString "$started_processes" "platform" 
       if [ $? -eq 0 ] ; then
          echolog 'Platform Agent $2 Running.' "\r\t\t\t\t"    
       else
          echolog 'Platform Agent $2 Not Running.' "\r\t\t\t\t"    
       fi
       
       for each_instance in $list_of_instances
       do
          /usr/bin/echo $running_instances | /usr/bin/grep -w $each_instance
          if [ $? -eq 0 ] ; then
             echolog 'Platform instance $2 $3 Running.' "$each_instance" "\r\t\t\t\t"    
          else
             echolog 'Platform instance $2 $3 Not Running.' "$each_instance" "\r\t\t\t\t" 
          fi
       done
    fi
   
    echolog '-------------------------------------------------------------------------------'

# /usr/bin/pkginfo -qi SUNWcstv
#                  [ $? -eq 0 ] && do_cstservice=1
#	          /usr/bin/pkginfo -qi SUNWcstve
#                  [ $? -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

}
    

find_present_port() {
   port=""
   if [ "$1" = "grouping" ] ; then
      port=""
      JAVASERVICE_CONFIG_FILE="${VAROPTDIR}/cfg/javaservice.properties"
      if [ -r "$JAVASERVICE_CONFIG_FILE" ] ; then
         port=`/usr/bin/cat "$JAVASERVICE_CONFIG_FILE" | /usr/bin/grep "ServiceRegistryPort" 2> /dev/null `
         port=`/usr/bin/echo "$port" | /usr/bin/cut -f2 -d=  `
      fi
   else
      if [ "$1" = "webserver_HTTP" -o  "$1" = "webserver_HTTPS"  ] ; then
         WEBSERVER_CONFIG_FILE="${BASEDIR}/web/conf/server.xml"
         if [ -r "$WEBSERVER_CONFIG_FILE" ]; then
             port=`/usr/bin/cat $WEBSERVER_CONFIG_FILE | /usr/bin/grep "port=" | /usr/bin/cut -f2 -d'=' | /usr/bin/cut -f2 -d'"'  2> /dev/null ` 
             port=`/usr/bin/echo $port  2> /dev/null `
             WEBPORT=`/usr/bin/echo $port | /usr/bin/cut -f2 -d' '  2> /dev/null `
             WEBPORTSSL=`/usr/bin/echo $port | /usr/bin/cut -f3 -d' '  2> /dev/null `
             [ "$1" = "webserver_HTTP" ] && port="$WEBPORT"
             [ "$1" = "webserver_HTTPS" ] && port="$WEBPORTSSL"
         fi
      else
          if [ "$1" = "rmi" ] ; then
             RMIRECEPTOR_CONFIG_FILE="$VARDIR/server-config.x"
             if [ -r "$RMIRECEPTOR_CONFIG_FILE" ]; then
                port=`/usr/bin/cat "$RMIRECEPTOR_CONFIG_FILE" | /usr/bin/grep "property:rmiPort"  2> /dev/null`
                port=`/usr/bin/echo "$port" | /usr/bin/cut -f2 -d=  2> /dev/null `
             fi
          else
             set_xput
             port=`$XGET "$VARDIR/domain-config.x" "$1.snmpPort"  2> /dev/null`
          fi
      fi
   fi
   port=`/usr/bin/echo $port  2> /dev/null `  # remove spaces
   [ -z "$port" ] && return 1
   return 0
}

# This function can be invoked for any sunmc version.
# This will list out SunMC installation details in following format
# ------------------------------------------------------------------
# Product	Status		Packages
# ------------------------------------------------------------------
# 
#
#
display_table_product_packages () {

    echolog ''
    echolog '-------------------------------------------------------------------------------'
    echolog 'Sun Management Center installation status:'
    echolog '-------------------------------------------------------------------------------'
    
    tmp_l_all_registry_packages=""
    for each_product in `$CMD_ECHO "$L_INSTALLED_PRODUCTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        tmp_prod_name=`get_product_names "$each_product"`     
        tmp_prod_name=`/usr/bin/echo $tmp_prod_name | /usr/bin/cut -c 1-41 `
        tmp_product_status=""
        tmp_l_components=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component" "key" 2> /dev/null `
        tmp_l_ok_packages=""
        tmp_l_failed_packages=""
        tmp_l_mismatch=""
        for each_component in `/usr/bin/echo "$tmp_l_components" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            tmp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package" "key" WHERE "status=1"  2> /dev/null `
            [ $? -gt 0 ] && echolog 'Registry read error.' && return 1
            tmp_l_ok_packages="$tmp_l_ok_packages $tmp_list"
            tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/,/ /g" 2> /dev/null `
             
            tmp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "component=$each_component" "package" "key" WHERE "status=0" 2> /dev/null `
            [ $? -gt 0 ] && echolog 'Registry read error.' && return 1
            tmp_l_failed_packages="$tmp_l_failed_packages $tmp_list"
            tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed s/,/ /g 2> /dev/null `
        done
        
        # Get oracle packages in case of server layer
        #
        if [ "$no_server" = "0" -a "$each_product" = "PRODUCT.PE" ]; then
           tmp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_package" "key" WHERE "status=1" 2> /dev/null `
           tmp_l_ok_packages="$tmp_l_ok_packages $tmp_list"
           tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/,/ /g" 2> /dev/null `
            
           tmp_list=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_package" "key" WHERE "status=0" 2> /dev/null `
           tmp_l_failed_packages="$tmp_l_failed_packages $tmp_list"
           tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed "s/,/ /g" 2> /dev/null `
        fi
      
        # Make both lists unique - No package name should be repeate :tmp_l_ok_packages
        #
        tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/ /,/g" `
        tmp_l_ok_packages="$tmp_l_ok_packages,@"
        for each_package in `$CMD_ECHO "$tmp_l_ok_packages" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/$each_package,/###/" `       
            tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/$each_package,//g" `       
            tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/###/$each_package,/" `
        done
        tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/@//" `
        tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/,/ /g" `
 
 
        # Make both lists unique - No package name should be repeate :tmp_l_failed_packages
        #
        tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed "s/ /,/g" `
        tmp_l_failed_packages="$tmp_l_failed_packages,@"
        for each_package in `$CMD_ECHO "$tmp_l_failed_packagess" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed "s/$each_package,/###/" `       
            tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed "s/$each_package,//g" `       
            tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed "s/###/$each_package,/" `
        done
        tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed "s/@//" `
        tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages | /usr/bin/sed "s/,/ /g" `
  
        # Find Registry mismatch of packages
        # FInd packages which are marked installed in Registry but are not actually on system.
        #
        for each_package in `$CMD_ECHO "$tmp_l_ok_packages" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
        do
            /usr/bin/pkginfo -qi $each_package > /dev/null 2>&1
            if [ $? -gt 0 ] ; then #Registry status mismatched
                
                tmp_l_mismatch="$tmp_l_mismatch $each_package"
                # Remove from OK list
                #
                tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages | /usr/bin/sed "s/$each_package//" `
 
                # Add to not OK list
                #
                tmp_l_failed_packages="$tmp_l_failed_packages $each_package"
            fi
        done
      
        tmp_l_ok_packages=`/usr/bin/echo $tmp_l_ok_packages  2> /dev/null  `
        tmp_l_failed_packages=`/usr/bin/echo $tmp_l_failed_packages 2> /dev/null  `
        tmp_l_all_registry_packages="$tmp_l_all_registry_packages $tmp_l_ok_packages $tmp_l_failed_packages"

        echolog 'PRODUCT$2: $3' "\r\t\t\t\t" "$tmp_prod_name"

        # Find if the product is in the list of setup products
        #
        #
        tmp_installation_status="Not Setup. Script will skip Setup checks."
        tmp_l_failed_layers=""
        if [ "$each_product" = "PRODUCT.PE" ] ; then
            [ "$no_agent" = "0" -a "$agent_setup" != "1" ] && tmp_l_failed_layers="agent"
            [ "$no_server" = "0" -a "$server_setup" != "1" ] && tmp_l_failed_layers="$tmp_l_failed_layers server"
            [ "$no_console" = "0" -a "$console_setup" != "1" ] && tmp_l_failed_layers="$tmp_l_failed_layers console"
            [ -z "$tmp_l_failed_layers" ] && tmp_installation_status="Setup."
            tmp_l_failed_layers=`/usr/bin/echo $tmp_l_failed_layers | /usr/bin/sed "s/ /,/g"  2> /dev/null`
        else
           /usr/bin/echo $L_ADDONS_SETUP | /usr/bin/grep "$each_product" > /dev/null 2>&1
           [ $? -eq 0 ] && tmp_installation_status="Setup."
        fi
        
        echolog 'INSTALLATION STATUS$2: $3' "\r\t\t\t\t" "$tmp_installation_status"
        if [ "$each_product" = "PRODUCT.PE" ] ; then
           [ ! -z "$tmp_l_failed_layers" ] && echolog 'LAYERS NOT SETUP$2: $3' "\r\t\t\t\t" "$tmp_l_failed_layers"
           if [ "$no_server" = "0" ] ; then
               if [ "$database_setup" = "1" ] ; then
                   echolog 'DATABASE SETUP$2: $3' "\r\t\t\t\t" "Setup."
               else
                   echolog 'DATABASE SETUP$2: $3' "\r\t\t\t\t" "Not Setup."
               fi
           fi
        fi
        
        
        if [ ! -z "$tmp_l_ok_packages" ] ; then
            #echolog 'COMPLETELY INSTALLED PACKAGES$2: $3' "\r\t\t\t\t" "$tmp_l_ok_packages"
            format_display "$tmp_l_ok_packages" 
            echolog 'COMPLETELY INSTALLED PACKAGES$2: $3' "\r\t\t\t\t" "$tmp_display_string"
        else
            echolog 'COMPLETELY INSTALLED PACKAGES$2: $3' "\r\t\t\t\t" "None."
        fi
        
        if [ ! -z "$tmp_l_failed_packages" ] ; then
            format_display "$tmp_l_failed_packages"
            echolog 'FAILED PACKAGES$2: $3' "\r\t\t\t\t" "$tmp_display_string"
        fi

	if [ ! -z "$tmp_l_failed_packages" ] ; then
	   echolog ''
	   echolog 'One or more packages are not installed correctly.'
	   echolog 'This product may not function correctly.'
	fi

        if [ ! -z "$tmp_l_mismatch" ]; then
            echolog ''
            format_display "$tmp_l_mismatch" 
            multiline_echolog 'Registry is not in sync with actual package status\nfor following packages$2: $3' "\r\t\t\t\t" "$tmp_display_string"
        fi
 
        echolog ''   
        echolog '-------------------------------------------------------------------------------'
    done 

    # Display extra symon packages (if any ) on system apart from all packages listed in Registry.
    # then 
    #
    tmp_l_all_symon_packages=`/usr/bin/pkginfo -c symon | /usr/bin/awk '{print $2}'`
    
    tmp_l_not_in_registry=""
    for each_package in `$CMD_ECHO "$tmp_l_all_symon_packages" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
        /usr/bin/echo "$tmp_l_all_registry_packages" | /usr/bin/grep -w "$each_package"  > /dev/null 2>&1
        [ $? -ne 0 ] && tmp_l_not_in_registry="$tmp_l_not_in_registry $each_package"
    done
    tmp_l_not_in_registry=`/usr/bin/echo $tmp_l_not_in_registry 2> /dev/null `
    if [ ! -z "$tmp_l_not_in_registry" ]; then
       echolog 'Found extra symon category packages on system.'
       echolog 'These packages are not listed in Registry.'
       format_display "$tmp_l_not_in_registry" 
       echolog 'OTHER PACKAGES$2: $3' "\r\t\t\t\t" "$tmp_display_string"
    fi
    
#    echolog '-------------------------------------------------------------------------------'


    unset tmp_prod_name tmp_l_failed_packages tmp_l_ok_packages tmp_l_components tmp_installation_status tmp_l_mismatch
    unset tmp_l_all_registry_packages tmp_l_all_symon_packages tmp_l_not_in_registry
}


#
# Input $1 = List with space as delimiter
# Returns = Sets tmp_display_string
#
format_display() {
  [ -z "$1" ] && return
   
  if [ -z "$2" ] ; then
     tmp_delim=","
  else
     tmp_delim="$2"
     [ "$2" = "0" ] && tmp_delim=" "
  fi
 
  display_list="$1"
  tmp_count=0
  tmp_display_string=""
  for each_item in `/usr/bin/echo "$display_list" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
  do
     tmp_count=`/usr/bin/expr $tmp_count + 1`
     if [ -z "$tmp_display_string" ] ; then
         tmp_display_string="$each_item"
     else 
        if [ $tmp_count -gt 4 ]; then
           tmp_count=1
           [ ! -z "$tmp_display_string" ] && tmp_display_string="${tmp_display_string}${tmp_delim}\n\r\t\t\t\t: $each_item"
       
       
       
        else
           tmp_display_string="${tmp_display_string}${tmp_delim}$each_item"
        fi       
     fi
  done
 
}


display_table_product_dependacies () {

    [ "$DO_ONLY_ONE_CHECK" = "1" ] && return

    echolog ''
    echolog '' 
    echolog 'Sun Management Center Add-Ons and Versions:'
    echolog '-------------------------------------------------------------------------------'
    echolog ' PRODUCT $2VERSION' "\r\t\t\t\t\t\t"
    echolog '-------------------------------------------------------------------------------'

    for each_product in `$CMD_ECHO "$L_INSTALLED_PRODUCTS" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
    do
    
         ## #Find dependant products from registry 
         ## #
         ## L_DEPENDANT=`get_dependant_products "$each_product" `
         tmp_str=`get_product_names "$each_product"`     
         tmp_str=`/usr/bin/echo $tmp_str | /usr/bin/cut -c 1-31 `
         
         tmp_version=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "version" 2> /dev/null `
         ## tmp_version=`/usr/bin/echo $tmp_version | /usr/bin/cut -c 1-3 `
         tmp_str="$tmp_str\r\t\t\t\t\t\t${tmp_version}\t"
         
         ## if [ ! "$L_DEPENDANT" ] ; then
         ##    if [ "$each_product" = "PRODUCT.PE" ] ; then
         ##       if [ ! -z "$L_INSTALLED_ADDONS" ]; then
         ##          tmp_str="$tmp_str\r\t\t\t\t\t All Addons\t"
         ##       else
         ##          tmp_str="$tmp_str\r\t\t\t\t\t None\t" 
         ##       fi
         ##    else
         ##       tmp_str="$tmp_str\r\t\t\t\t\t None\t"
         ##    fi
         ## fi

         ## for each_dependant in `$CMD_ECHO "$L_DEPENDANT" | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
         ## do 
         ##    tmp_prod_name=`get_product_names "$each_dependant"`
         ##    tmp_prod_name=`/usr/bin/echo $tmp_prod_name | /usr/bin/cut -c 1-48 `
         ##    tmp_str="$tmp_str\r\t\t\t\t\t `$tmp_prod_name\n"
         ## done

         echolog '$2' "$tmp_str"

    done
    
    echolog '-------------------------------------------------------------------------------'

}


display_table_patch_details() {
   
     [ "$DO_ONLY_ONE_CHECK" = "1" ] && return

     echolog ''
     echolog 'Sun Management Center Patch installation details:'
     echolog '-------------------------------------------------------------------------------'
     
     tmp_all_patch_info=`/usr/bin/showrev -p  2> /dev/null `
     patch_ids=`/usr/bin/showrev -p | /usr/bin/cut -f2 -d: | cut -d' ' -f2   2> /dev/null` 
    
     l_symon_patches=""
     l_patched_packages=""
     for each_patch in $patch_ids
     do
        tmp_patch=`/usr/bin/echo "$tmp_all_patch_info" | /usr/bin/grep -w "Patch: $each_patch"  2> /dev/null`
        check_package=`/usr/bin/showrev -p | /usr/bin/grep "Patch: $each_patch" | /usr/bin/cut -d : -f 6`
        check_package=`echo $check_package | /usr/bin/sed -e 's/,//g'`

        if [ ! -z "$check_package" ] ; then
            for each_package in $check_package 
            do
                category_value=`/usr/bin/pkgparam $each_package CATEGORY  2> /dev/null`
                /usr/bin/echo ${category_value} | /usr/bin/grep -i symon > /dev/null 2>&1
                if [ $? -eq 0 ] ; then
                     l_symon_patches="$l_symon_patches $each_patch"
                     l_patched_packages="$l_patched_packages $check_package"
                     
                fi
            done
        fi
     done
     #  Uncomment this for testing from simulated patch
     #l_symon_patches="11111-03 12232-04"
     
     
    
    
     
     if [ -z "$l_symon_patches" ]; then
         echolog 'No Sun Management Center patch is installed.'
     else
         # Added for testind. As we do not have any 3.5 patches
         #l_patched_packages="SUNWesip6 SUNWesloc SUNWesamn SUNWesae SUNWesagt SUNWesagt SUNWesnt SUNWesken SUNWescom SUNWeswsa"
         
        
         format_display "$l_symon_patches"
         echolog 'Installed patches$2: $3' "\r\t\t\t\t" "$tmp_display_string"
     
        
         l_patched_products=""
 
         l_avialable_products=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product" "key" 2> /dev/null `
         [ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"
        
         is_product_patched=0
         for each_product in `/usr/bin/echo "$l_avialable_products" | $CMD_AWK -F ',' '{ for (i = 1; i <= NF; i++) print $i }'`
         do
             l_packages_this_product=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_product" "package" "key" 2> /dev/null `
             l_packages_this_product=`/usr/bin/echo $l_packages_this_product | /usr/bin/sed "s/,/ /g" 2> /dev/null `
             is_product_patched=0
             l_patched_product_packages=""
             for each_patched_package in $l_patched_packages
             do
                 /usr/bin/echo $l_packages_this_product | /usr/bin/grep -w $each_patched_package  1>/dev/null 2>&1
                 if [ $? -eq 0 ] ; then
                     is_product_patched=1
                     l_patched_product_packages="$l_patched_product_packages $each_patched_package"
                 fi
             done
            
             if [ "$is_product_patched" = "1" ] ; then
                 format_display "$l_patched_product_packages"
                 echolog '$2$3: $4' "`get_product_names "$each_product"`" "\r\t\t\t\t" "$tmp_display_string"
                 l_patched_products="$l_patched_products $each_product"
             fi
         done

     fi
     echolog '-------------------------------------------------------------------------------'

}


debug () {

   

   echo L_INSTALLED_PRODUCTS $L_INSTALLED_PRODUCTS
   echo L_INSTALLED_ADDONS $L_INSTALLED_ADDONS
   echo no_server $no_server
   echo no_agent $no_agent
   echo no_console $no_console
   echo no_HA $no_HA
   echo no_DE $no_DE
   
   echo L_ADDONS_NOT_SETUP $L_ADDONS_NOT_SETUP 
   echo server_setup $server_setup
   echo console_setup $console_setup 
   echo agent_setup $agent_setup
   echo database_setup $database_setup
   echo L_BASE_SETUP_LAYERS $L_BASE_SETUP_LAYERS

}


debugs () {
    echo L_ALL_SUNMC_PRODUCTS $L_ALL_SUNMC_PRODUCTS
    echo L_COMPLETELY_INSTALLED_PACKAGES $L_COMPLETELY_INSTALLED_PACKAGES
    echo L_ALL_SUNMC_PACKAGES $L_ALL_SUNMC_PACKAGES
    echo L_PARTLY_INSTALLED_PACKAGES $L_PARTLY_INSTALLED_PACKAGES
}


reset_flags_ValTool () {

    EXIT_STATUS=1
    
}


# Find if installation of SUNWescom is correct and the version is 3.5
# If not, just inform  user the  symon  category  packages  and  exit
# If installation of SUNWescom found OK, then set BASEDIR if possible 
# and variables depending on it.
#
check_minimum_installation () {

    SUNMC_VERSION="WRONG_VERSION"
    /usr/bin/pkginfo -qi SUNWescom  > /dev/null 2>&1
    if [ $? -eq 0 ];then
        BASEDIR=`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon  ; export BASEDIR
        SYMONHOME=$BASEDIR ; export SYMONHOME
        ESROOT="$BASEDIR" ; export ESROOT   
        if [ -r "${SCRIPT_DIR}/es-common.sh" ] ; then
           SUNMC_VERSION=`/usr/bin/pkgparam SUNWescom SUNW_PRODVERS  2> /dev/null `
           /usr/bin/echo $SUNMC_VERSION | /usr/bin/grep "3.5" > /dev/null 2>&1
           if [ $? -eq 0 ]; then
               SUNMC_VERSION="3.5"
           else
              /usr/bin/echo "Invalid version of Sun Management Center."
           fi
        fi
    else
       /usr/bin/echo "Basic Sun Management Center package is missing or not installed correctly."
    fi

    if [ "$SUNMC_VERSION" != "3.5" ] ; then
        L_SYMON_PACKAGES=`/usr/bin/pkginfo -c symon | /usr/bin/awk '{print $2}'`
        if [ ! -z "$L_SYMON_PACKAGES" ] ; then 
           /usr/bin/echo '-------------------------------------------------------------------------------'
           /usr/bin/echo "Following Sun Managenet Center packages are installed on the system:"
           L_SYMON_PACKAGES=`/usr/bin/echo $L_SYMON_PACKAGES | /usr/bin/sed "s/ /,/g" 2> /dev/null `
           /usr/bin/echo $L_SYMON_PACKAGES
           /usr/bin/echo '-------------------------------------------------------------------------------'
        fi
    
        tmp_all_patch_info=`/usr/bin/showrev -p  2> /dev/null `
        patch_ids=`/usr/bin/showrev -p | /usr/bin/cut -f2 -d: | cut -d' ' -f2   2> /dev/null` 
    
        l_symon_patches=""
        l_patched_packages=""
        for each_patch in $patch_ids
        do
           tmp_patch=`/usr/bin/echo "$tmp_all_patch_info" | /usr/bin/grep -w "Patch: $each_patch"  2> /dev/null`

           check_package=`/usr/bin/showrev -p | /usr/bin/grep "Patch: $each_patch" | /usr/bin/cut -d : -f 6`
           check_package=`echo $check_package | /usr/bin/sed -e 's/,//g'`

           if [ ! -z "$check_package" ] ; then
               for each_package in $check_package 
               do
                  category_value=`/usr/bin/pkgparam $each_package CATEGORY  2> /dev/null`
                  /usr/bin/echo ${category_value} | /usr/bin/grep -i symon > /dev/null 2>&1
                  if [ $? -eq 0 ] ; then
                      l_symon_patches="$l_symon_patches $each_patch"
                      l_patched_packages="$l_patched_packages $check_package"
                      break
                  fi
               done
           fi
        done
        /usr/bin/echo ''
        /usr/bin/echo '-------------------------------------------------------------------------------'
        if [ -z "$l_symon_patches" ]; then
            /usr/bin/echo 'No Sun Management Center patches installed.'
        else
            /usr/bin/echo 'Following Sun Management Center patches are installed:' 
             l_symon_patches=`/usr/bin/echo $l_symon_patches | /usr/bin/sed "s/ /,/g" 2> /dev/null `
            /usr/bin/echo "$l_symon_patches"
            /usr/bin/echo 'Following Sun Management Center packages are patched:' 
            /usr/bin/echo patched packages are $l_patched_packages
        fi
        /usr/bin/echo '-------------------------------------------------------------------------------'
         
        exit 1
    fi

    export SUNMC_VERSION
}


set_environment_ValTool () {
    
    /usr/bin/clear > /dev/null 2>&1
    /usr/bin/stty tabs > /dev/null 2>&1
   
    [ -x /usr/bin/tabs ] && /usr/bin/tabs -8 
   
    DATE_FORMAT=`eval echo "+\\\%y\\\%m\\\%d\\\%H\\\%M\\\%S"`
    TIMESTAMP=`/usr/bin/date $DATE_FORMAT`
    HOST=`/usr/bin/hostname`
    [ -z "$LOGFILE" ] && LOGFILE="/tmp/validation_$HOST.$TIMESTAMP.$$"	
    
    if [ ! -f "$LOGFILE" ] ; then
        /usr/bin/touch "$LOGFILE" >/dev/null 2>&1
        /usr/bin/chmod 640 "$LOGFILE"
        if [ $? -ne 0 ] ; then
            echo ""
            eval echo `/usr/bin/gettext 'Unable to create logfile : $LOGFILE.'`
            LOGFILE="/tmp/validation_$HOST.$TIMESTAMP.$$"	
        fi
    fi
   
    #
    # Ensure that script is called by superuser and set proper umask
    #
    #check_root
    umask 022

    #
    # Set BASEDIR,VAROPTDIR,CONFIGDIR,SYMONHOME etc...
    # 
    set_inst_base_dir
    set_basedir 

    echolog ''
    echolog '-------------------------------------------------------------------------------'
    echolog 'This script will help you in validation of Sun \\(TM\\) Management Center.'
    echolog '-------------------------------------------------------------------------------'
   
    #
    # Set Registry location and initialize Registry if version is 3.5
    # 
    [ "$SUNMC_VERSION" = "3.5" ] && initializeRegistry
   
    # Create log file and find OS version, rest all flags to default.
    #
    
    
    check_osver

    reset_flags_ValTool

    
    get_util_dir
    reset_all_validation_flags
    
    #
    # Returns :
    #    1. Install related: 
    #           L_BASE_INSTALLED_LAYERS,L_INSTALLED_PRODUCTS,L_INSTALLED_ADDONS  no_server,no_agent,no_console, no_HA, no_DE
    #    2. Setup Related:
    #           L_ADDONS_NOT_SETUP => "ADDON1 ADDON2 ..." in order of **DEPENDANCIES**
    #           server_setup, console_setup agent_setup & database_setup L_BASE_SETUP_LAYERS
    #
    get_SunMC_setup_status

    [ $no_server -eq 0 -o $no_agent -eq 0 ] && set_xput

    # if server name is not given on commandline and localhost is server
    if [ $no_server -eq 0 ] && [ "$S_OPT" = "N" ]
    then
        SERVER_NAME=`/usr/bin/hostname`
    fi
  
}


validate_node_details () {
    show_config
    convert_host_to_address
}


select_validation_todo () {

    echolog ''
    echolog '-------------------------------------------------------------------------------'
    echolog 'This script will help you in validation of Sun \\(TM\\) Management Center.'
    echolog '-------------------------------------------------------------------------------'

}



# >>>>>>>>>>>>>> Generic functions >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

# Shell implementation of substr(4)
# This can be used for tabular listing of data 
# In bourn shell. This will avoid use of carriage return char 
# which bumps when used with telnet.
#
# Input $1 - String 1  SHOULD NOT CONTAIN '#' character
#       $2 - String 2
#       $3 - termination length of string 1 ( should not be more that 50 )
#            If $1 is smaller. then extraspaces will be introduced
# Returns
#       echos resultant string.
#
attach_string () {
    tmp_buff="################################################################################"
    tmp_str="${1}${tmp_buff}"
    tmp_str=`/usr/bin/echo "$tmp_str" | /usr/bin/cut -c 1-"$3" 2> /dev/null`
    tmp_str="$tmp_str ${2}"
    tmp_str=`/usr/bin/echo $tmp_str | /usr/bin/sed "s/#/ /g" 2> /dev/null`
    /usr/bin/echo "$tmp_str"
    unset tmp_buff tmp_str
}


exit_validationtool() {
   
    #/usr/bin/rm -rf /tmp/SunMCInstall 

    echolog ''
    [ ! -z "$LOGFILE" ] && echolog 'Validation tool Log file is : $2 ' "$LOGFILE"

    exit 0
}


get_agent_version() {
    #.iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.base.info.agent.general.oaversion
   
    snmpout=`$UTIL_DIR/snmpget -h $1 -p $2 -c public -t 10 1.3.6.1.4.1.42.2.12.2.1.2.2.1.1.0 2> /dev/null `

    echo $snmpout|/usr/bin/grep "Error: noError"|/usr/bin/grep -v grep > /dev/null
    if [ $? -eq 0 ]
    then
        echo $snmpout | /usr/bin/cut -d'"' -f2
    else
        echolog 'Error finding agent version of $2:$3 .' $1 $2
        return 1
    fi
    return 0
}

    
check_proper_configd() {
    
    if [ ! -f $BASEDIR/addons/AdvancedMonitoring/sbin/configd-check.sh ]
    then
        return 1
    fi

    . $BASEDIR/addons/AdvancedMonitoring/sbin/configd-check.sh
    
    configd_check
    ret=$?
    if [ $ret -eq 0 ]
    then
        echo "Config Reader appropriate to this machine is installed"
    else 
        echo "Config Reader appropriate to this machine is not installed"
        return 2
    fi

    return 0
}


validate_addons_scripts() {
    
    #BASEDIR=`/usr/bin/pkginfo -r SUNWescom`/SUNWsymon
    ADDONS_DIR=$BASEDIR/addons
    [ ! -d "$ADDONS_DIR" ] && return
    
    VALUSER="$USER"
    VALPASS="$PASSWORD"
    VALSERVERHOST="$SERVER"
    VALSERVERPORT="$PORT"
    export VALUSER VALPASS VALSERVERHOST VALSERVERPORT
    
    echo ""
    FLAG_ANY="N"
    for each in `/usr/bin/ls -1 $ADDONS_DIR`
    do
        ADDON_VAL=$ADDONS_DIR/$each/sbin/es-validate
        if [ -f "$ADDON_VAL" ] 
        then
            if [ $FLAG_ANY = "N" ] 
            then
                echo "Calling Validation code of addons:"
                echo "-------------------------------------------------------------------------------"
                FLAG_ANY="Y"
            fi
            echo "Executing $ADDON_VAL"
            sh "$ADDON_VAL"
        fi
    done
    
}



############################################################################
# Main Starts here
############################################################################
#initialising variables
PROGNAME=$0
export PROGNAME
PREV_DIR=`/usr/bin/pwd`
SCRIPT_DIR=`/usr/bin/dirname $PROGNAME`
TOOLS_DIR=${SCRIPT_DIR}/../lib/sbin
PATH="$PATH:${SCRIPT_DIR}:${TOOLS_DIR}"
VERSION="3.5 alpha"
USER=""
PASSWORD=""
#SERVER_NAME=`/usr/bin/hostname`
SERVER_NAME=""
SERVER="$SERVER_NAME"
PORT=2099
VERBOSE=""
NPASS=0
NFAIL=0
NINDET=0
TESTS=0
AGENT_LIST=""
DO_ONLY_ONE_CHECK=0

trap 'terminate' 1 2 3 15

# Since validation tool is part of base product we can assume it is installed.
BASEDIR=`pkgparam SUNWescom BASEDIR`
. ${BASEDIR}/SUNWsymon/sbin/es-common.sh
set_basedir

process_options_ValTool "$@"
check_minimum_installation


set_environment_ValTool
validate_node_details
validate_installation_details
validate_setup_details
validate_misc_features
validate_functionality_details
validate_addons_scripts
exit_validationtool

