#!/bin/sh
# Copyright 01/11/05 Sun Microsystems, Inc. All Rights Reserved.
# pragma ident  "@(#)setup-functions.sh	1.130 05/01/11 Sun Microsystems"
#
# Main functions in this script
# 1.print_usage_setup()
# 2.process_options_setup()
# 3.reset_flags_setup()
# 4.setup_base_product()
# 5.setup_HA()
# 6.save_setup_response_summary()
# 7.exit_SunMC()

# Prints usage for es-setup
# ACDFHhruvw
print_usage_setup() {
    eval /usr/bin/echo "\"`/usr/bin/gettext  'Usage: $PROGNAME [ -A file ] [ -C file ] [ -p dir ] [ -Fhrvw ]\n Where the options represent:\n'`\""
    /usr/bin/echo ""
    /usr/bin/gettext ' Default : Setup   Base   product  and  all  addons  in  incremental  mode.\n'
    /usr/bin/gettext ' -A<file>: Do an automated setup based  on the  specified  Response Summary\n           file. This option will be ignored if the -C option is specified.\n           This file should have been generated  through an earlier install\n           (with setup) or setup using -C.\n'
    /usr/bin/gettext ' -C<file>: Specifies a  Response  Summary file to  store user inputs during\n           this setup. This option  will supersede the -A option. This file\n           will be used for future automated setup.\n'
    /usr/bin/gettext ' -p<name>: Setup a  single  Addon by  force. This  will re-setup  specified\n           Addon even if it is already setup. The  name to be  provided  is\n           the directory name for the add-on.\n'
    /usr/bin/gettext ' -F:       Setup Base product and  all installed  Addon products  by force.\n'
    /usr/bin/gettext ' -h:       Prints this usage.\n'
    /usr/bin/gettext ' -k:       Perform setup without generating security keys.\n'
    /usr/bin/gettext ' -r:       Recreate database.\n'
    /usr/bin/gettext ' -v:       Verbose mode.\n'
    /usr/bin/gettext ' -w:       Skip Database re-setup.  This  option  is  valid with -F option.\n'
    /usr/bin/echo ""
}


# Checks for argument & sets uninst flags accordingly
# ACDFHhruvw
#
process_options_setup() {
    if [ ! -z "$1" ]; then
        /usr/bin/echo "$@" | /usr/bin/grep "-" > /dev/null 2>&1
        [ $? -eq 1 ] && print_usage_setup && exit "$ARGUMENTS_ERROR"
            
        arg_count=0       
        while getopts A:C:D:p:FHbehkrvw OPT
        do
            case $OPT in
                A)  # Valid with all other options also
                    #
                    AUTOCONFIG_RUNFILE=`getPathName $OPTARG`
                    ;;

                C)  # -A option will be ignored with this option
                    # 
                    AUTOCONFIG_SAVEFILE=`getPathName $OPTARG`
                    ;;

                D)  # INVALID with -FHru options
                    #
                    force_addon_only_flag=1
                    ADDON_DIR="$OPTARG"
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;
                p)  # Same as -p just to keep backward compatibility 
                    #
                    force_addon_only_flag=1
                    ADDON_DIR="$OPTARG"
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;

                F)  # INVALID with -D 
                    # This will also do all functions done by r,u options
                    #
                    force_base_flag=1
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;

                H)  # INVALID with -D, -r, 
                    # Optional with Default,-F
                    #
                    setup_HA_flag=1
                    ;;

                b)  # This option is for smart-update
                    # If this option specified, setup will not redirect the questions to console
                    # instead it will exit if TAG not found in response summary file
                    #
                    setup_base_only=1
	            ;;
                e)  # This option is for smart-update
                    # If this option specified, setup will not redirect the questions to console
                    # instead it will exit if TAG not found in response summary file
                    #
                    flash_questions_to_console=0
                    export flash_questions_to_console
                    ;;
                h)  print_usage_setup
                    exit_SunMC_setup  "$NO_ERROR"
                    ;;

                k)  # Avoid generation of security keys
                    #
                    generate_security_keys=0
                    export generate_security_keys
                    ;;

                r)  # Setup can be called with this option ALONE
                    # INVALID with -DFH option
                    recreate_database_flag=1
                    arg_count=`/usr/bin/expr "$arg_count" + 1`
                    ;;

                    #u)  # Setup can be called with this option ALONE
                    # This will also do all functions done by -r options
                    #
                    #do_default=1
                    #arg_count=`/usr/bin/expr "$arg_count" + 1`
                    #;;
 
                v)  verbose_flag=1s
                    VERBOSE="ON"
                    ;;

                w)  skip_database_flag=1
                    ;;
               
                *)  print_usage_setup
                    exit "$ARGUMENTS_ERROR"
                    ;;
            esac
        done

        wrong_arguments=0

        if [ $arg_count -gt 1 ]; then
           echolog 'Invalid Combination:$2' "$@"
           wrong_arguments=1
        else
           # -wr
           if [ $skip_database_flag -eq 1 -a $recreate_database_flag -eq 1 ]; then
              echolog 'Invalid Combination:$2' "$@"
              wrong_arguments=1
           else
              # -e option alone 
              if [ -z "$AUTOCONFIG_RUNFILE" -a "$flash_questions_to_console" = "0" ]; then
                 echolog 'This option is only valid if input summary file is specified.'
                 wrong_arguments=1
              fi
           fi
        fi
   
        if [ $wrong_arguments -eq 1 ]; then
            print_usage_setup
            exit "$ARGUMENTS_ERROR"
        fi

    fi        
    
    unset arg_count wrong_arguments

}
set_pid_for_gui() {
    [ ! -d "${TMP_DIR}" ] && /usr/bin/mkdir -p ${TMP_DIR}
    /usr/bin/echo "$$" > ${TMP_DIR}/es-setup.pid

}
# Setup a general environment globals setup
#
#
set_setup_environment() {

   umask 022

   # This sets BASEDIR,VAROPTDIR,CONFIGDIR,SYMONHOME etc...
   # 
   set_inst_base_dir
   set_basedir

   # Ensure the script is called by root

   check_root

   # Create any missing links for Solaris 10
   # create_s10_links

   checkOSVersion

   # Since no relocation rleated stuff with the
   # setup call the temp dir related functions
   # with blank parameters.

   remove_temp_directory
 
   create_temp_directory

   # If user presses "Stop" and tries to abort
   # the setup in between the GUI should have a 
   # way of killing all the setup related processes.
   # Store the pid in a temp file for the time being.

   set_pid_for_gui


   /usr/bin/echo $PROGNAME | grep "es-setup" > /dev/null 2>&1 
   [ $? -eq 0 ]  &&  /usr/bin/clear
   
   # Set Registry location
   #
   initializeRegistry
   
   [ ! -d "$VAROPTDIR" ] && /usr/bin/mkdir -p "$VAROPTDIR"
   /usr/bin/chmod 755 "$VAROPTDIR"

   IESROOT=$BASEDIR; export IESROOT

   # Create log file setup.PID.... 
   # Skip creation of LOGFILE by es-setup 
   # in case called by the GUI Setup
   # as the logfile is already present
   # and need not be created again 
   # Check if GUI_SETUP is 1, which
   # indicates that the GUI is calling the setup
   # and promptly skip the creation of the logfile
   # once more.

   [ "$GUI_SETUP" != "1" ] && unset LOGFILE

   check_logfile "setup"

   
   # Paths for Makefiles
   #
   set_paths
   
   check_osver

   # Sets setup flags to default values
   #
   reset_flags_setup

   # This will exit if system is not rebooted after /etc/system file modified
   #
   check_reboot_required

   # Remove the port list file 
   #
   L_ALL_SUNMC_PORTS="" 
   /usr/bin/rm -f ${TMP_DIR}/sunmc_ports.x

   # Restore echo if user aborts setup
   trap "/usr/bin/stty echo; exit" 2 3
 
}


# Input : None
# Returns : - Exits with proper exit status if machine is not rebooted after last run ofsetup  
#             modified the /etc/system file
#             Else returns 0
#
check_reboot_required() {

  if [ -f $VAROPTDIR/cfg/lastboot ]; then
    
     /usr/bin/who -b > ${TMP_DIR}/temp_file
     /usr/bin/cmp ${TMP_DIR}/temp_file  $VAROPTDIR/cfg/lastboot >/dev/null 2>&1
     if [ $? -eq 0 ]; then
        echolog ''
        echolog 'Last run of es-setup modified Kernel parameters.'
        echolog 'You must reboot the system for these changes to be effective.'
        exit_SunMC_setup  "$REBOOT_REQUIRED_ERROR"
     else
        rm -f $$VAROPTDIR/cfg/lastboot
     fi  

  fi

  return 0

}


# Sets / Restes all flags used by setup to default value
# Input   : None
# Returns : None
#
reset_flags_setup(){
   setup_base_only=0

   flash_questions_to_console=1
   generate_security_keys=1
   recreate_database_flag=0
   do_default=0
   #resp_summary_in=0
   #resp_summary_out=0
   force_addon_only_flag=0
   force_base_flag=0
   setup_HA_flag=0
   verbose_flag=0
   skip_database_flag=0
   EXIT_STATUS=0 
   VERBOSE="OFF"
   
   DB_CLEAN_EXPL="FALSE"
   DB_USER_EXIST="TRUE"
   DB_GROUP_EXIST="TRUE"

   update_registry_flag=0

   CORE_DATA_PRESERVED=1

   export flash_questions_to_console generate_security_keys 

}



# Depending on the arguments specified, selects the setup to do.
# Input   : reads all flags set by process_arguments_setup
# Returns : - Sets all XXX_required flags
#           - Displays the user the selection => what is going to be setup
#
select_setup_todo() {

   server_setup_required=0
   agent_setup_required=0
   console_setup_required=0
   database_setup_required=0
   
   if [ $no_server -eq 1 -a $no_agent -eq 1 -a $no_console -eq 1 ]; then
     echolog 'Nothing is installed. You must install Sun Management Center first.'
     exit_SunMC_setup  "$BAD_INSTALLATION_ERROR"
   fi   
   
   if [ $recreate_database_flag -eq 1 -o $do_default -eq 1 -o $skip_database_flag -eq 1 -o $force_addon_only_flag -eq 1 ] ; then
      if [ $server_setup -eq 0 -a $agent_setup -eq 0 -a $console_setup -eq 0 ]; then
         echolog ''
         echolog 'None of the base layers is setup.'
         echolog 'Arguments -p / -r / -w are valid only if base product is setup.'
         echolog 'Run es-setup in default mode to setup base product.'
         echolog ''
         exit_SunMC_setup "$BAD_INSTALLATION_ERROR"
      fi
   fi
   
   if [ $do_default -eq 1 ] ; then
      if [ $server_setup -eq 0 -a $agent_setup -eq 0 ]; then
         echolog ''
         echolog 'Neither Server nor Agent is setup.'
         #echolog 'Can not bring Sun Management Center to default state.'
         echolog ''
         exit_SunMC_setup "$NO_ERROR"
      fi
   else
      if [ $recreate_database_flag -eq 1 ]; then
         if [ $no_server -eq 0 -a $server_setup -eq 1 ]; then
            database_setup_required=1
            database_setup=0
         else
            echolog 'Server is not setup. Can not Recreate Database.'
            exit_SunMC_setup "$DATABASE_ERROR"
         fi
      else
         if [ $no_server -eq 0 ]; then
            
            if [ $server_setup -eq 0 -o $force_base_flag -eq 1 ]; then

               server_setup_required=1
               server_setup=0
               agent_setup=0
               L_UNSET_LAYERS="LAYER.SERVER"

               if [ "$database_setup" = "1" ]; then
                  [ $skip_database_flag -eq 0 ] && database_setup_required=1 && database_setup=0
               else
                  database_setup_required=1 && database_setup=0
               fi
            
            fi
            
            if [ $server_setup -eq 1 -a "$database_setup" != "1" ]; then
               database_setup_required=1 && database_setup=0
            fi
         fi
   
         if [ $no_agent -eq 0 ]; then
            if [ $agent_setup -eq 0 -o $force_base_flag -eq 1 ]; then
               L_UNSET_LAYERS="$L_UNSET_LAYERS LAYER.AGENT"
               agent_setup_required=1
               agent_setup=0
            fi
         fi
   
         if [ $no_console -eq 0 ]; then
            if [ $console_setup -eq 0 -o $force_base_flag -eq 1 ]; then
               console_setup_required=1
               console_setup=0
               L_UNSET_LAYERS="$L_UNSET_LAYERS LAYER.CONSOLE."
            fi
         fi
   
         L_UNSET_LAYERS=`/usr/bin/echo $L_UNSET_LAYERS | /usr/bin/sed "s/ /,/g" `
 
         # Come up with a list of products which will get setup L_SETUP_SURE
         # This list will be in the order of dependancies & not the 
         # order in which products are placed in registry
         # 
         if [ $force_addon_only_flag -eq 1 ]; then
      
            [ -z "$ADDON_DIR" ] && exit_SunMC_setup  "$ADDON_DIR_ERROR"
            
            # Find Addon KEY ID from addon dir
            found_flag=0
            for each_addon in `$CMD_ECHO $L_INSTALLED_ADDONS | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`         
            do 
 
                temp_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "target_subdir"  2> /dev/null `
                #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
                 
     
                if [ "$temp_dir" = "$ADDON_DIR" ];then
                   addon_id=$each_addon
                   found_flag=1
                   break
                fi
            done
            
            if [ $found_flag -eq 0 ]; then
               echolog 'Setup script for addon $2 not present.' "$ADDON_DIR"
               exit_SunMC_setup  "$ADDON_DIR_ERROR"
            fi
                  
            # Select specified addon & all dependant addons for setup
            #
            
            temp_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$addon_id" "depends-on"  2> /dev/null `
            #[ $? -gt 0 ] && exit_SunMC_uninstall "$REGISTRY_READ_ERROR"
            
            temp_list=`/usr/bin/echo $temp_list | /usr/bin/sed "s/,/ /g" `
            L_ADDON_SETUP_TODO="$temp_list $addon_id"
         else
            #if [ $force_base_flag -eq 1 ]; then
            if [ $force_base_flag -eq 1 ]; then
                L_ADDON_SETUP_TODO=$L_INSTALLED_ADDONS
            else
                L_ADDON_SETUP_TODO=$L_ADDONS_NOT_SETUP
            fi
         fi
      fi
   fi

   [ "$setup_base_only" = "1" ] && L_ADDON_SETUP_TODO=""
   
   # Now onwards for any exit, update registry
   #
   update_registry_flag=1

   echolog ''
   echolog '----------------------------------------------------------------------------'
   echolog 'This script will help you to setup Sun \\(TM\\) Management Center 3.5 Update 1.'
   echolog '----------------------------------------------------------------------------'
              
   

   if [ $do_default -eq 1 ] ; then
      echolog ''
      echolog 'This will bring setup to factory default.'
      echolog ''
      return 
   fi


   if [ "$L_BASE_INSTALLED_LAYERS" ] ; then
      echologverbose ''
      echologverbose 'Following layer[s] are installed:$2' "`get_layer_name "$L_BASE_INSTALLED_LAYERS"`"
   fi
   
   if [ "$L_BASE_SETUP_LAYERS" ] ; then
      echologverbose ''
      echologverbose 'Following layer[s] are already setup: $2' "`get_layer_name "$L_BASE_SETUP_LAYERS"`"
   else
      echologverbose ''
      echologverbose 'None of the layers is setup.' 
   fi
   
   if [ "$L_UNSET_LAYERS" ] ; then
      echologverbose ''
      echologverbose 'Following layer[s] will get setup: $2' "`get_layer_name "$L_UNSET_LAYERS"`"
   else
      echologverbose ''
      echologverbose 'Base layers are already setup.'
   fi
  
   echologverbose ''
   if [ $database_setup_required -eq 1 ]; then
      if [ $skip_database_flag -eq 1 ] ; then
          echologverbose 'Database is not yet setup'      
      fi
      echologverbose 'Database will be setup.'
   else
      echologverbose 'Database will not be setup.'
   fi
  
   if [ "$L_INSTALLED_ADDONS" ] ; then
      echologverbose 'Following Addon[s] are installed:$2$3.' "\n" "`get_product_names "$L_INSTALLED_ADDONS"`"
   else
      echologverbose 'Addon installation not found.'
   fi
 
   if [ "$L_ADDONS_SETUP" ] ; then
      echologverbose ''
      echologverbose 'Following Addon[s] are already setup:$2$3.' "\n" "`get_product_names "$L_ADDONS_SETUP"`"
   fi

   if [ "$L_ADDON_SETUP_TODO" ] ; then
      echologverbose ''
      echologverbose 'Following Addon[s] will get setup:$2$3.' "\n" "`get_product_names "$L_ADDON_SETUP_TODO"`"
   fi

   if [ -z "$L_ADDON_SETUP_TODO"  -a $database_setup_required -eq 0 -a -z "$L_UNSET_LAYERS" ]; then
      echolog ''
      echolog 'Setup could not find any Sun Management Center component pending for setup.'
      echolog 'You can use $2/sbin/es-setup -F to force re-setup of all installed components.' "$BASEDIR"
      exit_SunMC "$NO_ERROR"
   fi

   echologverbose ''
   unset  temp_list
}

# Stop SunMC if it is not a addon_only setup
#
stop_SunMC_old() {
   if [ $server_setup_required -eq 1 -o $agent_setup_required -eq 1 ]; then
      if [ "$server_setup" = "1" -a "$agent_setup" = "1" ] ; then
         echolog 'Stoping Sun Management Center...'
         $BASEDIR/sbin/es-stop -A
      else
         [ "$agent_setup" = "1" ] && echolog 'Stoping Sun Management Center...' && $BASEDIR/sbin/es-stop -a
      fi

      if [ "$server_setup" = "1" ] ; then
         kill_processes "discover"
      fi
   fi
}


# check the addressing mode
# If user has enabled NAT already using es-config, 
# default it back to "ip" and give user a warning.
#
check_for_addressing_mode () {
   # if only console installed, just return
   #
   [ $no_agent -eq 1 -a $no_server -eq 1 ] && return

   set_xput

   if [ "$server_setup_required" = "1" -o "$agent_setup_required" = "1" ] ; then

      LOGICAL_ADDRESS_MODE="ip" 
      
      tmp_config_file="$VAROPTDIR/cfg/domain-config.x"
      if [ -r "$tmp_config_file" ] ; then
         set_xput
         LogicalAddressMode=`$XGET $tmp_config_file agent.logicalAddressMode`
         if [ "$LogicalAddressMode" = "name" ] ; then
             if [ "$force_base_flag" =  "0" ] ; then # This means its upgrade
                LOGICAL_ADDRESS_MODE="name"
             else
                echolog ''
                multiline_echolog 'WARNING : This host is configured to work in a NAT environment.\nSetup will remove NAT support by default.\nYou must use $2 to enable NAT support after setup.'  "$BASEDIR/sbin/es-config -n" 
             fi
         fi
         unset LogicalAddressMode
      fi
      unset tmp_config_file
   fi

   export LOGICAL_ADDRESS_MODE
}

# Validates the hostname.
# $1 - Hostname
# Return: 0 if pingable
#         otherwise non zero error code

validate_host()
{

        name="$1"

        /usr/sbin/ping $name > /dev/null 2> /dev/null
        return $?
}

# validates and ip address
# returns 1 if valid ip address
# returns 0 otherwise
#
isIpAddress () {

    ipaddress="$1"

    #
    # ensure ipaddress is valid
    #
    ipaddr=`echo $ipaddress | /usr/bin/egrep '^[1-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?\.[0-9][0-9]?[0-9]?$'`
    if [ -z "$ipaddr" ] ; then
       return 0
    fi

    return 1
}

# Stop SunMC if it is not a addon_only setup
#
stop_SunMC() {

   #if [ $server_setup_required -eq 1 -a $agent_setup_required -eq 1 ]; then
   if [ $no_server -eq 0 -a $no_agent -eq 0 ]; then

      sunmc_running=0
      # 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
         [ $? -eq 0 ] && sunmc_running=1
      fi
      
      # /usr/ucb/ps -wwagx | grep ServerMain | grep -v "grep"  > /dev/null 2>&1
      # [ $? -eq 0 ] && sunmc_running=1
      
      # Find all other SunMC compoments running 
      #
      started_processes=`ps -ef -o "args" | grep "esd - init" | grep -v grep` 2> /dev/null
      [ ! -z "$started_processes" ] && sunmc_running=1

      # Finf 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
         [ $? -eq 0 ] && sunmc_running=1
      fi

      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
          [ $? -eq 0 ] && sunmc_running=1
      fi    
      
      # Find if grouping service running or not
      #
      #/usr/ucb/ps -wwagx | /usr/bin/fgrep java | /usr/bin/fgrep mgmtservice.main.SunMCServices | /usr/bin/fgrep -v /usr/bin/fgrep  > /dev/null 2>&1
      #[ $? -eq 0 ] && sunmc_running=1
  
      # Find if database is running
      #
      get_lsnr_and_ora_proc_count
      [ $lcnt -gt 0 -o $scnt -gt 0 ] && sunmc_running=1
        
      if [ "$sunmc_running" = "1" ] ; then
         echolog ''
         echolog 'Setup found some Sun management Center processes running.'
         if [ "$no_HA" = "1" ] ; then
            echolog 'Stopping Sun management Center...'
            $BASEDIR/sbin/es-stop -A
 	    get_lsnr_and_ora_proc_count
 	    if [ $lcnt -gt 0 -o $scnt -gt 0 ]
 	    then
     	       	# forcefully kill Sun Management Center database processes
            	echolog ''
            	echolog "Need to forcefully kill the database processes, please wait..."
		set_db_env
            	kill_ora_processes
 	    fi
            kill_all_processes "discover" "KILL"
         else
            echolog 'Use the stopSunMC script to stop Sun Management Center before attempting setup on Sun Management Center HA server.'
            exit_SunMC "$SERVICE_STOP_ERROR"
         fi
      fi
      #
      # Clean up any shared memory kept by smcorau.
      # In case there are no database processes are running but shared memory is held up.
	set_db_env
	release_shm_sems "$SMCORAU" "$SMCORAG"

      return

   fi

   if [ $no_agent -eq 0 ]; then
      sunmc_running=0
      started_processes=`/bin/ps -ef -o "args" | /bin/grep "esd - init" | grep -v grep` 2> /dev/null
      [ ! -z "$started_processes" ] && $BASEDIR/sbin/es-stop -Yla 
      echolog ''
      return
   fi
}


   
# This will set default factory settings
# Call es-setup.sh -u for all the addon products if they have es-setup.sh
# Recreate the complete data base. This will blow away any thing in database.
# Blow away other data like .x files in /var/opt/SUNWsymon/cfg directory.
# Update registry.
# 
bring_SunMC_to_default() {

   # Call es-setup.sh -u for all the addon products if they have es-setup.sh
   #
   for each_addon in `$CMD_ECHO $L_ADDONS_SETUP | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do 
      addon_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "target_subdir" 2> /dev/null`
      #[ $? -gt 0 ] &&  exit_SunMC "$REGISTRY_READ_ERROR"
      
      if [ -f "$BASEDIR/addons/$addon_dir/sbin/es-setup.sh" ]; then
         [ "$setup_base_only" != "1" ] && $BASEDIR/addons/$addon_dir/sbin/es-setup.sh -u
      fi
   done
  
   # Recreate the complete data base. This will blow away any thing in database.
   #
   #setup_sunmc_database
   #database_setup=1
   
   # Blow away other data like .x files in /var/opt/SUNWsymon/cfg
   #
   rm -f /var/opt/SUNWsymon/cfg/*.x

   server_setup=0
   agent_setup=0
   console_setup=0
   database_setup=0
   L_ADDON_SETUP_TODO=$L_INSTALLED_ADDONS
   update_registry_setup

   exit_SunMC_setup "$NO_ERROR"
   
}

# Setup Java
#
setup_java() {
  
    # Setup Java if required
    #

    if [ $no_server -eq 0 -o $no_console -eq 0 ] ; then
        checkJavaOK
        if [ $? -ne 0 ] ; then            
            echolog 'You must install a supported JDK and re-run setup.'
            exit_SunMC "$JAVA_ERROR"       
        fi
        if [ ! -f "${VAROPTDIR}/cfg/java.home" ] ; then            
            /usr/bin/cat << !EOF > "${VAROPTDIR}/cfg/java.home"
# 
# DO NOT REMOVE COMMENTS
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# Auto JAVA_HOME detection file for Sun Management Center 3.5 
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# 
# A  minimum of  Solaris JDK 1.3.1 is required for  Console Components.
# A  minimum of  Solaris JDK 1.4   is required for  Server  Components.
#
# You  may set the  environment variable JAVA_HOME, or edit  this  file 
# to point  to the  *BASE*  directory of a valid JDK  installation. The
# \$JAVA_HOME/bin/java  and \$JAVA_HOME/bin/jar executables will be  used.
# Otherwise, java is searched for at /usr/j2se and finally at /usr/java. 
#       
# An  example of  specifying  JAVA_HOME is shown below.  Uncomment  the 
# following line and modify /usr/java to point to your JDK installation.
#JAVA_HOME=/usr/java
!EOF
        fi
    fi 
}


# save cfg file
#
save_config_info() {
   
   # Note : .cfginfo is not a published interface.
   # This interface is maintained in 3.5 just to keep backward compatibility.
   # PRM and SYSRM addons are using this interface. 
   #
   # Please note that this list slightly differs from component_list defined 
   # earlier in script ( Note the diff - Server <=> server )
   #
   [ $server_setup -eq 1 ] && cfg_component_list="Server"
   [ $agent_setup -eq 1 ] && cfg_component_list="$cfg_component_list Agent"
   [ $server_setup -eq 1 ] && cfg_component_list="$cfg_component_list Metadata"
   [ $console_setup -eq 1 ] && cfg_component_list="$cfg_component_list Console"
   [ $server_setup -eq 1 ] && cfg_component_list="$cfg_component_list Services"
   
   
    # Setup has been successful so put this information into cfginfo file.
    #
    /usr/bin/touch  "$BASEDIR/sbin/.cfginfo"
    put_var_in_cfgfile  "$BASEDIR/sbin/.cfginfo" "SETUP_COMPONENTS" "$cfg_component_list" "="
    if [ $? -ne 0 ] ; then
       echolog 'Error: It seems the file $2 is not writable, could not update the file.' "$BASEDIR/sbin/.cfginfo"
    fi
    /usr/bin/chmod 644 "$BASEDIR/sbin/.cfginfo"
 
    unset cfg_component_list
}

# THIS FUNCTION WILL BE CALLED BY TRAP HANDLER
#
# Input: $1 - ERORR_CODE
# Returns : saves response file & exits with proper exit_status
#
exit_SunMC_setup(){

  [ "$update_registry_flag" != "1" ] && exit $1

  if [ "$1" = "$REBOOT_REQUIRED" ]; then
     if [ -z "$AUTOCONFIG_RUNFILE" ]; then
          echolog 'Press RETURN to exit...'
          read pause
          exit $1
     fi
  fi

  #
  # Save setup related vars/LISTS
  #
  echologverbose ''

  if [ $1 -ne 0 ] ; then

     # Update registry
     #
     if [ $1 -ne $REGISTRY_READ_ERROR -a $1 -ne $REGISTRY_WRITE_ERROR -a $1 -ne $REGISTRY_PERMISSION_ERROR ]; then
        update_registry_setup
     else
        echolog 'Setup encountered an error while accessing Registry.'     
     fi

  fi
  
  if [ $1 -ne $REGISTRY_READ_ERROR -a $1 -ne $REGISTRY_WRITE_ERROR -a $1 -ne $REGISTRY_PERMISSION_ERROR ]; then
      display_setup_status_to_user
  fi
  
  # Exit with proper exit status - $1
  #
  echolog ''
  if [ $1 -eq 0 ]; then
     echolog 'Setup of Sun Management Center is complete.'
     [ ! -z "$LOGFILE" ] && echolog 'Setup logfile is : $2 ' "$LOGFILE"
  else
     [ "$1" -ne "$USER_ABORT_ERROR" ] && [ "$1" != "$REBOOT_REQUIRED" ] && echolog 'Could not finish requested task.'
     echo " "
  fi 

  exit $1

}



# Clears junk files related to Advanced Monitoring Pack
#
clear_junk_files() {
   
   [ $server_setup_required -eq 0 ] && return 0
   
   # Copy one x file which will be removed by Advanced Monitoring Pack installation.
   #
   if [ -f "$BASEDIR/classes/base/console/cfg/applications-process-core-j.x" ] ; then
      /usr/bin/cp -f "$BASEDIR/classes/base/console/cfg/applications-process-core-j.x" "$VARDIR/applications-process-j.x"
      /usr/bin/chmod 644 "$VARDIR/applications-process-j.x"
   fi
   
   # create dummy x file which will be removed by Advanced Monitoring Pack installation.
   #
   if [ -f "$VARDIR/details-tab-viewlog-j.x" ] ; then
      /usr/bin/rm -f "$VARDIR/details-tab-viewlog-j.x"
   fi  
   
   /usr/bin/touch "$VARDIR/details-tab-viewlog-j.x"

}

# $1 = script name
# $2 = component name
#
run_setup() {

   HA_ARGC=""
   [ $setup_HA_flag -eq 1 ] && HA_ARGC="-H"
   
   if [ $verbose_flag -eq 1 ] ; then
      $BASEDIR/lib/sbin/$1 -v -s "$security_seed" "$HA_ARGC"
      retcode=$?
   else
      $BASEDIR/lib/sbin/$1 -s "$security_seed" "$HA_ARGC"
      retcode=$?
   fi

   if [ $retcode -ne 0 ] ; then
      echolog ''
      [ $retcode -ne "$USER_ABORT_ERROR" ] && echolog 'Setup of $2 component failed.' "$2"
      exit_SunMC_setup  "$COMPONENT_SETUP_ERROR"
   fi 
   #   if [ "$2" = "Console" -o "$2" = "Server" -o "$2" = "Agent" ]; then
   #      echolog ''
   #      echolog 'Setup of $2 component is successful.' "$2"
   #   fi

}


# Input : $1 = setup script name
#         $2 = component name
# Returns :
setup_component() {

    # hack to preserve i18n for console setup
    if [ $1 = sm_setup_console.sh ]; then
        SETUP_LIST="$SETUP_LIST Console"
        echolog ''
        echolog 'Setup of Console component is successful.' 
        return 0
    fi

    if [ $1 = sm_setup_service.sh ]; then
        SETUP_LIST="$SETUP_LIST Services"
        return 0
    fi

    if [ ! -f "$BASEDIR/lib/sbin/$1" ]; then
	multiline_echolog 'The Sun Management Center Setup File $2$3\nis missing. Cannot Setup Sun Management Center $4.' "$BASEDIR" "/lib/sbin/$1" "$2"
	echolog ""
	exit_SunMC_setup  "$COMPONENT_SETUP_ERROR"
    fi

    SETUP_LIST="$SETUP_LIST $2"
    echologverbose ""
    echologverbose 'Initiating setup for Sun Management Center $2 Component.' $2
    run_setup $1 $2
    return 0
}

# Input : L_ADDON_SETUP_TODO
# Functionality : First gets addon target directory from from registry & then
#                 call setup script for that directory  for each addon in a list       
# Returns :  Updates L_ADDON_SETUP_TODO
#            sets L_ADDON_SETUP_FAILED
#            sets L_ADDON_SCRIPT_NOT_FOUND
#            sets L_ADDON_SETUP_DONE
#
setup_addons () {
   [ -z "$@" ] && return
   $CMD_ECHO " "
   echolog 'Setting up Addon[s]...'

		set_basedir
		ServerName=`$XGET ${VARDIR}/domain-config.x agent.agentServer`
		tmp_dir=$VAROPTDIR/install 
		addon_tmp_sql=$tmp_dir/addon_tmp_sql.$ServerName
		addon_sql=$tmp_dir/addon_sql.$ServerName

#
# Setting up env variable to indicate es-machine not to execute stored proc. Instead write sql calls to file.
#
   ES_DEVICE_DB_SYNC="lazy"
   export  ES_DEVICE_DB_SYNC
   if [ -f "$addon_sql" ]; then
		#  
		#This is to handle special case if previous es-setup had exited abruptly.  
		#Update the addon registry in database irrespective of ES_DEVICE_DB_SYNC mode if addon_sql file exists.
		#  
		update_db_addon_registry	
		$CMD_RM $addon_sql
	fi

   $CMD_TOUCH  "$addon_sql" 
   brkCode=0
   [ $server_setup -eq 1 ] && component_list="server" && L_SETUP_LAYERS="$L_SETUP_LAYERS LAYER.SERVER"
   [ $agent_setup -eq 1 ] && component_list="$component_list agent"  && L_SETUP_LAYERS="$L_SETUP_LAYERS LAYER.AGENT"
   [ $server_setup -eq 1 ] && component_list="$component_list metadata"
   [ $console_setup -eq 1 ] && component_list="$component_list console" && L_SETUP_LAYERS="$L_SETUP_LAYERS LAYER.CONSOLE"
   [ $server_setup -eq 1 ] && component_list="$component_list services"
   L_INSTALLED_LAYERS="$L_BASE_INSTALLED_LAYERS"
   export  L_INSTALLED_LAYERS  L_SETUP_LAYERS L_INSTALLED_ADDONS CORE_DATA_PRESERVED

   for each_addon in `$CMD_ECHO $@ | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do 
      export L_ADDON_SCRIPT_NOT_FOUND L_ADDON_SETUP_TODO L_ADDON_SETUP_DONE L_ADDON_SETUP_FAILED 
   
      addon_dir=`$API_QUERY_REGISTRY "$REGISTRY" "category=SunMC" "product=$each_addon" "target_subdir" 2> /dev/null`
      #[ $? -gt 0 ] &&  exit_SunMC "$REGISTRY_READ_ERROR"

    if [ -f "$addon_tmp_sql" ] ; then
        # remove the file
        $CMD_RM $addon_tmp_sql
    fi

    $CMD_TOUCH  $addon_tmp_sql 

      if [ -f "$BASEDIR/addons/$addon_dir/sbin/es-setup.sh" ]; then

          ( $BASEDIR/addons/$addon_dir/sbin/es-setup.sh $component_list  )
          retcode=$? 
          if [ $retcode -gt 0 ]; then
             L_ADDON_SETUP_FAILED="$L_ADDON_SETUP_FAILED $each_addon"
             [ $retcode -eq 255 ] && continue # This means user selected NO in addon setup script. Go to next addon
             [ $retcode -eq 2 ] && brkCode=1 && break # This means opted to quit from setup itself. Do not update requistry in this case.
             $CMD_CAT  $addon_tmp_sql >> $addon_sql 
             echolog ""
             echolog  'A problem occurred with $2 setup.'  "`get_product_names "$each_addon"`"

             READ_RESPONSE_ONCE=0
             fetch_response_yes_no "TAG=CONTINUE_IF_ADDON_FAILS" 'Do you want to continue ' 
             [ $? -gt 0 ]  && brkCode=2 && break
             saveAutoConfig "CONTINUE_IF_ADDON_FAILS" "$answer"
             [ $answer -eq 0 ] && brkCode=3 && break 

          else
             L_ADDON_SETUP_TODO=`/usr/bin/echo $L_ADDON_SETUP_TODO | /usr/bin/sed "s/$each_addon//"`
             L_ADDON_SETUP_DONE="$L_ADDON_SETUP_DONE $each_addon"
             $CMD_CAT  $addon_tmp_sql >> $addon_sql 
          fi 

      else
         L_ADDON_SCRIPT_NOT_FOUND="$L_ADDON_SCRIPT_NOT_FOUND $each_addon"
         L_ADDON_SETUP_TODO=`/usr/bin/echo $L_ADDON_SETUP_TODO | /usr/bin/sed "s/$each_addon//"`
         L_ADDON_SETUP_DONE="$L_ADDON_SETUP_DONE $each_addon"
         $CMD_CAT  $addon_tmp_sql >> $addon_sql 
      fi

   done
   ES_DEVICE_DB_SYNC="immediate"
   update_db_addon_registry
#
# Remove the sql files here 
#
   $CMD_RM $addon_tmp_sql
   $CMD_RM $addon_sql

#
# If user opts to discontinue or quit setup 
#
   case $brkCode in

            1)  exit
                ;;

            2)  exit_SunMC "$SUMMARY_READ_ERROR"
                ;;

            3)  exit_SunMC_setup  "$ADDON_SETUP_ERROR"
                ;;

            *)  return 0
                ;;
    esac

}

#
# It starts the DB and updates all family files in single DB connection
#

update_db_addon_registry() {

	set_basedir
	tmp_dir=$VAROPTDIR/install
	ServerName=`$XGET ${VARDIR}/domain-config.x agent.agentServer`
	addon_sql=$tmp_dir/addon_sql.$ServerName

#
# check if the family registry file  has data
#

   count=`$CMD_CAT $addon_sql | $CMD_WC -l `

   if [ $count -eq 0 ]; then
      #
      #  No data in the SQL file
      #
      return 0
   fi

   echolog "Updating the Addon[s] family registry in database. Please wait.."
   set_db_env
   create_temp_directory

   . ${BASEDIR}/lib/sbin/db-common.sh
   . $BASEDIR/db/cfg/dbadmin.cfg

   SQLPLUS=$ORACLE_HOME/bin/sqlplus

#
# start the database if not already running
#
   check_Oracle_running
   if [ $? -eq 0 ]; then
      #
      # oracle is not running
      #
      db_start
   fi

#
# Insert family data in db
#

   for each_sql in `$CMD_CAT $addon_sql  | awk '{ print $1 }'`
   do

     tmpfile=$TMP_DIR/machine.$$
     /usr/bin/rm -f $tmpfile

     db_runProc "$each_sql" $SUNMC_USER $SUNMC_USER_PWD $tmpfile
     sql_retcode=$?
     if [ $sql_retcode -ne 0 ] ; then
         echolog "setup-functions:update_db_addon_registry failed"
         exit 1
     fi

   done

   echolog  "Addon[s] registry updated.. "
#
# stop db 
#
   db_stop

}


setup_device_type()
{
    if [ ! -d $VARDIR ] ; then
        /usr/bin/mkdir -p $VARDIR
    fi

    if [  -f $VARDIR/deviceinfo.conf ] ; then
        return 0
    fi

    device_platform=`/usr/bin/uname -p`
    os_release=`/usr/bin/uname -r | sed 's/^5/2/' | cut -d\. -f1,2`

    LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$BASEDIR/base/lib"
    export LD_LIBRARY_PATH

    gsioutput=""
    gsioutput=`$BASEDIR/base/bin/deviceinfo 2> /dev/null`

    if [ -z "$gsioutput" ] ; then
        return 0
    fi

    did=`echo $gsioutput | /usr/bin/nawk ' { print $1 } ' `
    oid=`echo $gsioutput | /usr/bin/nawk ' { print $2 } ' `
    ftype=`echo $gsioutput | /usr/bin/nawk ' { print $3 } ' `

    if [ -z "$did" -o -z "$oid" -o -z "$ftype" ] ; then
         echolog "Read the release notes to configure the device type."
         return 0
    fi

    echo "DID             $did" > $VARDIR/deviceinfo.conf
    echo "OID             $oid" >> $VARDIR/deviceinfo.conf
    echo "FAMILYTYPE      $ftype" >> $VARDIR/deviceinfo.conf
    return 0

}

update_registry_setup() {
   
   echologverbose ''
   echologverbose 'Updating registry...'

   # If any of the server layer / Datbase is failed, marked both as failed 
   #
   if [ "$database_setup_required" =  "1" -a "$database_setup" = "0" -a "$server_setup" = "1" ] ; then
      echologverbose 'As database is not setup, Marking server setup as failed in Registry.'
      server_setup=0
   fi

   L_BASE_INSTALLED_LAYERS=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer" "key" 2> /dev/null `
   #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_READ_ERROR"

   checkString "$L_BASE_INSTALLED_LAYERS" "LAYER.SERVER"
   if [ $? -eq 0 ]; then
      $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "layer=LAYER.SERVER" "setup-status=$server_setup"  > /dev/null 2>&1 
      #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"

   fi
   
   checkString "$L_BASE_INSTALLED_LAYERS" "LAYER.AGENT"
   if [ $? -eq 0 ]; then
      $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "setup-status=$agent_setup"  > /dev/null 2>&1 
      #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"
   fi

   checkString "$L_BASE_INSTALLED_LAYERS" "LAYER.CONSOLE"
   if [ $? -eq 0 ]; then
      $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "layer=LAYER.CONSOLE" "setup-status=$console_setup"  > /dev/null 2>&1 
      #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"
   fi
   
   if [ -n "$database_setup" ] ; then 
      $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "database_setup=$database_setup"  > /dev/null 2>&1 
      #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"
   fi
   
   # Mark all addos setup in registry
   #
   
   for each_addon in `$CMD_ECHO $L_ADDON_SETUP_DONE | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do
      $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=$each_addon" "setup-status=1" > /dev/null 2>&1 
      #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"
   done

   # Mark all failed addons too...
   # This was $L_ADDON_SETUP_FAILED before
   #
   for each_addon in `$CMD_ECHO $L_ADDON_SETUP_TODO | $CMD_AWK -F ' ' '{ for (i = 1; i <= NF; i++) print $i }'`
   do
      $API_SET_ATTRIBUTE "$REGISTRY" "category=SunMC" "product=$each_addon" "setup-status=0" > /dev/null 2>&1 
      #[ $? -gt 0 ] && exit_SunMC "$REGISTRY_WRITE_ERROR"
   done


}

copy_locale_files() {

    /usr/bin/pkginfo -qi SUNWescom 2> /dev/null
    if [ $? -eq 0 ] ; then
        OPT_DIR="`/usr/bin/pkgparam SUNWescom BASEDIR`/SUNWsymon/lib/locale"
        /usr/bin/cp -rf $OPT_DIR $VAROPTDIR > /dev/null 2>&1
    fi

}

display_setup_status_to_user() {

   get_SunMC_setup_status

   echologverbose ''
   
   if [ "$L_BASE_SETUP_LAYERS" ]; then
      echologverbose 'Following Layers are setup:$2' "`get_layer_name "$L_BASE_SETUP_LAYERS"`"
   else
      echologverbose 'None of the base layers are setup.'
   fi
   
   echologverbose ''

   if [ "$server_setup" = "1" ]; then
      database_setup=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "database_setup"  2> /dev/null `
      if [ "$database_setup" = "1" ]; then
         echologverbose 'Database is setup sucessfully.'
      else
         echologverbose 'Database is not setup sucessfully.'
      fi
   fi
   
   echologverbose ''

   if [ "$L_ADDONS_SETUP" ]; then
      echologverbose 'Following Addons are setup:$2' "`get_product_names "$L_ADDONS_SETUP"`"
   else
      echologverbose 'No Addon is setup.'
   fi

   if [ "$L_ADDONS_NOT_SETUP" ]; then
      echologverbose 'Following Addons are not yet setup:$2' "`get_product_names "$L_ADDONS_NOT_SETUP"`"
   else
      [ "$L_INSTALLED_ADDONS" ] &&  echologverbose 'All installed Addons are setup.'
   fi

   echologverbose ''
   
}


start_SunMC () {
   echolog ''
   # return in case of console only installation
   #
   [ $no_server -eq 1 -a $no_agent -eq 1 ] && return 0

   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
       if [ $? -eq 0 ] ; then
           echolog 'Sun Management Center java server is already running.'
           multiline_echolog 'It is recommended that you should run $2/sbin/es-stop -A\nbefore starting Sun Management Center.' "$BASEDIR" 
       fi
   fi

   READ_RESPONSE_ONCE=0 
   if [ $no_server -eq 0 ]; then
      if [ "$install_on_cluster" != "1" ] ; then
         fetch_response_yes_no "TAG=START_SUNMC" "Do you want to start Sun Management Center agent and server components now "
         [ $? -gt 0 ] && exit_SunMC "$SUMMARY_READ_ERROR"
         saveAutoConfig "START_SUNMC" "$answer"
         if [ "$answer" = "1" ];then
            $BASEDIR/sbin/es-start -A
         else
            echolog 'Use $2/sbin/es-start -A to start Sun Management Center.' "$BASEDIR" 
         fi
      fi
   else
      fetch_response_yes_no "TAG=START_SUNMC" "Do you want to start Sun Management Center agent now "
      [ $? -gt 0 ] && exit_SunMC "$SUMMARY_READ_ERROR"
      saveAutoConfig "START_SUNMC" "$answer"
      CONF_FILE=$CONFDIR/symon.conf
      if [ "$answer" = "1" ];then
         # start agent only
         #
         echolog 'Starting Sun Management Center Agent...'
         $BASEDIR/sbin/es-start -a
         if [ -f "$CONF_FILE" ] ; then
            /usr/bin/grep platform "$CONF_FILE" > /dev/null
            if [ $? -eq 0 ] ; then
               $BASEDIR/sbin/es-start -lY > /dev/null 2>&1
            fi
         fi
      else
         /usr/bin/grep platform "$CONF_FILE" > /dev/null 2>&1
         if [ $? -eq 0 ] ; then
              echolog 'Use $2/sbin/es-start -al to start Sun Management Center agent and platform agent.' "$BASEDIR"
         else
              echolog 'Use $2/sbin/es-start -a to start Sun Management Center agent.' "$BASEDIR"
         fi
      fi
   fi
}

get_ex_args() {
	/usr/bin/ex - /tmp/symon_temp.$$ <<SYMONEOF >/dev/null 2>&1
a
.
w
q
SYMONEOF
    if [ $? -eq 0 ] ; then
	SM_EX_ARGS="-"
    else
	SM_EX_ARGS=""
    fi
    export SM_EX_ARGS

    if [ -f /tmp/symon_temp.$$ ] ; then
	/usr/sbin/unlink /tmp/symon_temp.$$
    fi
}

process_sma () {
    # Return if no Sun Management Center component is using 161
    # Ask user to disable traditional snmpdx daemon otherwise
    #
    set_xput
    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 161  > /dev/null
    [ $? -ne 0 ] && return # SMA default port 161 not used by any of the SunMC component.

    sma_on_161=0
    sma_pid=`/bin/pgrep -x snmpd`
    if [ ! -z "$sma_pid" ]; then
	# SMA (snmpd) is running
	/bin/pfiles $sma_pid | /bin/grep -w 'port: 161' > /dev/null 2>&1
	if [ $? -eq 0 ]; then
	    sma_on_161=1
	fi
    else
	isSMAOn161
	sma_on_161=$?
    fi
    if [ $sma_on_161 -eq 1 ]; then
	echolog ''
	multiline_echolog 'WARNING: You have selected the SunMC agent to run on the default port 161,\nwhich is currently used by Solaris System Management Agent (SMA).  If you\nare running on Solaris 10, the SMA automatically uses port 161.  The SMA\n(process snmpd) is based on the SNMPv3 protocol and it is *NOT* advisable\nto disable it.  We recommend that you run the  SunMC agent on a different\nport.\nIf you choose to run the SunMC agent on port 161, do the following:\n1. Make sure SMA is stopped before starting the SunMC agent.\n2. Disable the starting up of SMA at boot time.\nIf the SMA is not disabled, the SunMC agent will *NOT* start after a\nreboot.'

	READ_RESPONSE_ONCE=0
        fetch_response_yes_no "TAG=CONTINUE_IF_SMA_PRESENT" 'Do you want to continue? ' 
        [ $answer -ne 1 ] && exit_SunMC_setup "$NO_ERROR"
    fi
}


# Check if snmpdx is running (A)
# Check if snmpdx is configured for starting at boot time. (B)
# [ B=true ] then ask user for disabling/killing snmpdx from at boot time and do it if user says yes.
#                    This will also kill presently running snmpdx proc if any
# [ A=true ] then ask user if he wants to stop snmpdx, if yes,stop it.
# [ A=false and B=false] then Do nothing
#
disable_snmpdx_daemon() {

   # Return if no Sun Management Center component is using 161
   # Ask user to disable traditional snmpdx daemon otherwise
   #
   set_xput
   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 161  > /dev/null
   [ $? -ne 0 ] && return # SNMPDX port 161 not used by any of the SunMC component.

   # != "0" means snmpdx found - A
   snmpdx_running_proc=`/usr/bin/ps -aef | /usr/bin/fgrep -v grep | /usr/bin/grep snmpdx | /usr/bin/wc -l 2> /dev/null `
   snmpdx_running_proc=`/usr/bin/echo $snmpdx_running_proc 2> /dev/null `

   # if configured at boot time - B
   snmpdx_at_boot_time=0
   if [ -x "/etc/rc3.d/S76snmpdx" -o -x "/etc/rc3.d/S77dmi" ] ; then
      snmpdx_at_boot_time=1
   fi

   if [ "$snmpdx_at_boot_time" = "1" ]; then
      echolog ''
      multiline_echolog 'SNMP Daemon snmpdx is configured to start at boot time on this system.\nPort 161 will be used by Sun Management Center. The SNMP Daemon snmpdx uses\nport 161 by default, and might be set to start automatically during\nreboot. You can stop the daemon and prevent it from starting\nautomatically during reboot by disabling SNMP Daemon snmpdx now.'
      [ "$snmpdx_running_proc" != "0" ] && echolog 'Disabling the process will terminate SNMP Daemon snmpdx.'
      READ_RESPONSE_ONCE=0
      fetch_response_yes_no "TAG=DISABLE_SNMPDX_DAEMON" "Do you want to disable SNMP Daemon snmpdx "
      [ $? -gt 0 ] && exit_SunMC "$SUMMARY_READ_ERROR"
      saveAutoConfig "DISABLE_SNMPDX_DAEMON" "$answer"
      if [ $answer -eq 1 ] ; then
         if [ -x "/etc/rc3.d/S76snmpdx" ]; then
            /etc/rc3.d/S76snmpdx stop > /dev/null 2>&1 
            /usr/bin/mv -f /etc/rc3.d/S76snmpdx /etc/rc3.d/D.sunmc.S76snmpdx > /dev/null 2>&1 
            [ $? -eq 0 ] && echologverbose '/etc/rc3.d/S76snmpdx renamed as /etc/rc3.d/D.sunmc.S76snmpdx'
         fi
         if [ -x "/etc/rc3.d/S77dmi" ] ; then
            /etc/rc3.d/S77dmi stop > /dev/null 2>&1 
            /usr/bin/mv -f /etc/rc3.d/S77dmi /etc/rc3.d/D.sunmc.S77dmi > /dev/null 2>&1 
            [ $? -eq 0 ] && echologverbose '/etc/rc3.d/S77dmi renamed as /etc/rc3.d/D.sunmc.S77dmi'
         fi
         kill_all_processes "snmpdx" "KILL"
         kill_all_processes "snmpXdmid" "KILL"
      else
         if [ $answer -eq 0 ] ; then
         echolog ''
         echolog 'NOTE: Prior to starting Sun Management Center agent, stop the process using port 161.'
	 fi

      fi
      echolog '' 
      return
   fi

   if [ "$snmpdx_running_proc" != "0" ]; then 
      echolog ''
      echolog 'Setup found SNMPDX process running on this system.'
      echolog 'Port 161 will be used by Sun Management Center. The SNMPDX daemon uses'
      echolog 'port 161 by default, and might prevent Sun Management Center from starting.'
      echolog 'You can stop the SNMPDX daemon now to avoid port conflict.'
      READ_RESPONSE_ONCE=0
      fetch_response_yes_no "TAG=STOP_SNMPDX" "Do you want to stop SNMPDX "
      [ $? -gt 0 ] && exit_SunMC "$SUMMARY_READ_ERROR"
      saveAutoConfig "DISABLE_SNMPDX_DAEMON" "$answer"
      if [ $answer -eq 1 ] ; then
         kill_all_processes "snmpdx" "KILL"
         kill_all_processes "snmpXdmid" "KILL"
      fi
      echolog '' 
      return
   fi
}

# Asks user the logical hostname of SunMC server on cluster.
# 
get_HA_information () {

   install_on_cluster=1
   /usr/bin/pkginfo -qi SUNWscr > /dev/null 2>&1
   cluster_absent=$?
   
   /usr/bin/pkginfo -qi SUNWSunMC > /dev/null 2>&1
   HA_packages_absent=$?
   
   if [ $cluster_absent -eq 0 -a $HA_packages_absent -eq 0 ]; then
      install_on_cluster=1
   else
      install_on_cluster=0
      if [ $setup_HA_flag -eq 1 ]; then
         echolog ''
         echolog 'Could not find cluster intallation.'
         exit_SunMC "$BAD_INSTALLATION_ERROR"
      fi
   fi
   
   [ "$no_HA" != "0" ] && install_on_cluster=0
   
   if [ "$install_on_cluster" = "1" ]; then
  
      # Get cluster hostname
      #
      echolog ''
      retcode=1
      READ_RESPONSE_ONCE=0
      while [ $retcode -ne 0 ]; do
         fetch_response_text "TAG=SUNMC_SERVER" 'Enter the logical hostname of cluster:'
         [ $? -gt 0 ] && exit_SunMC "$INVALID_SunMC_SERVER_ERROR"          
         [ ! -z "$answer" ] && retcode=0
         [ $retcode -eq 0 ] && saveAutoConfig "SUNMC_SERVER" "$server_host" && break
      done
      HA_SERVER=$answer
      export HA_SERVER

      if [ "$agent_setup_required" = "1" ]; then
         # Get ESDIR
         #
         DEFAULT_ESDIR="$VAROPTDIR"
      
         echolog ''
         READ_RESPONSE_ONCE=0    
         while [ 1 ] ; do
            fetch_response_text "TAG=AGENT_CONFIG_DIRECTORY" "Enter the Agent Configuration directory relative to /var/opt [ SymonAgent ] :"
            [ $? -gt 0 ] && exit_SunMC "$SUMMARY_READ_ERROR"
            AGENT_ESDIR="/var/opt/$answer"
            [ "$answer" = "SUNWsymon" ] && echolog 'The server and agent directories must be different' && continue
            [ -z "$answer" ] && [ -z "$AUTOCONFIG_RUNFILE" ] && AGENT_ESDIR="/var/opt/SymonAgent"
            /usr/bin/mkdir -p "$AGENT_ESDIR"
            retstat=$? && [ $retstat -gt 0 ] && echolog 'Can not create agent setup directory.' && exit_SunMC "$DIR_ACCESS_ERROR"
            chmod 755 "$AGENT_ESDIR"
            retstat=$? && [ $? -gt 0 ] && echolog 'chmod failed on agent setup directory.'  && exit_SunMC "$DIR_ACCESS_ERROR"
         
            if [ $retstat -eq 0 ] ; then
               break
            else
               echolog 'Could not setup agent in /var/opt/$2' "$AGENT_ESDIR" 
               if [ "$flash_questions_to_console" = "1" ] ; then
                  fetch_response_yes_no 'Do you want to specify other location '
                  [ $answer -eq 0 ] &&  echolog 'Exiting agent setup...' && exit_SunMC "$DIR_ACCESS_ERROR"
               else
                  exit_SunMC "$SUMMARY_READ_ERROR"
               fi
            fi
         done     
         echolog ''
         saveAutoConfig "AGENT_CONFIG_DIRECTORY" "$AGENT_ESDIR"
      fi
   else
      AGENT_ESDIR="$VAROPTDIR"
   fi
  
   [ $no_agent -eq 0 ] && $API_SET_ATTRIBUTE "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir=$AGENT_ESDIR" > /dev/null 2>&1
   
   export AGENT_ESDIR DEFAULT_ESDIR install_on_cluster
   
}

# In case of HA setup, replace hostname in database configuration files with 
# logical hostname of cluster
#
update_for_logical_hostname () {
   
   echologverbose 'Updating oracle files for logical hostname...'
   current_host=`/usr/bin/hostname`
   
   # Update initSunMC.ora
   #
   current_file="$ORACLE_HOME/admin/SunMC/pfile/initSunMC.ora"
   /usr/bin/mv $current_file /tmp/initSunMC.ora.tmp
   /usr/bin/cat /tmp/initSunMC.ora.tmp | /usr/bin/sed s/"HOST=$current_host"/"HOST=$HA_SERVER"/ > $current_file
   chmod 444 $current_file
   chown smcorau:smcorag $current_file
   /usr/bin/rm -f /tmp/initSunMC.ora.tmp
   
   
   # listener.ora
   #
   current_file="$ORACLE_HOME/network/admin/listener.ora"
   /usr/bin/mv $current_file /tmp/listener.ora.tmp
   /usr/bin/cat /tmp/listener.ora.tmp | /usr/bin/sed s/"HOST = $current_host"/"HOST = $HA_SERVER"/ > $current_file
   chmod 464 $current_file
   chown smcorau:smcorag $current_file
   /usr/bin/rm -f /tmp/listener.ora.tmp
   
   # Update tnsnames.ora
   #
   current_file="$ORACLE_HOME/network/admin/tnsnames.ora"
   /usr/bin/mv $current_file /tmp/tnsnames.ora.tmp
   /usr/bin/cat /tmp/tnsnames.ora.tmp | /usr/bin/sed s/"HOST = $current_host"/"HOST = $HA_SERVER"/ > $current_file
   chmod 464 $current_file
   chown smcorau:smcorag $current_file
   /usr/bin/rm -f /tmp/tnsnames.ora.tmp

   if [ -f "${VAROPTDIR}/web/server_hosts" ]; then
      /usr/bin/chmod u+w ${VAROPTDIR}/web/server_hosts
      /usr/bin/mv -f ${VAROPTDIR}/web/server_hosts ${VAROPTDIR}/web/server_hosts.old
      /usr/bin/echo  "$HA_SERVER" > ${VAROPTDIR}/web/server_hosts
   fi   
   
   if [ -f "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties" ]; then
       [ ! -d $VAROPTDIR/cfg ] && /bin/mkdir $VAROPTDIR/cfg
       [ -f "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties" ] && /usr/bin/mv -f "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties" "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties.old"
       /usr/bin/cp "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties.old" /tmp/alternativeservice.properties
       /usr/bin/cat /tmp/alternativeservice.properties | /usr/bin/grep -v "AlternateServiceHost"  > "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties"
       /usr/bin/echo  "AlternateServiceHost = $HA_SERVER:$HA_SERVER\n" >> "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties"
       /usr/bin/rm -f /tmp/alternativeservice.properties 
   fi
   
   
   ESDIR="$AGENT_ESDIR"
   set_basedir
   set_xput
   agent_port=`$XGET ${VARDIR}/domain-config.x agent.snmpPort`
   ESDIR="/var/opt/SUNWsymon"
   set_basedir
   set_xput
   $XPUT ${VARDIR}/domain-config.x agent.snmpPort $agent_port
   
   unset current_file
}

# Undo HA related changes in oracle config files 
# This is required in case of force run of setup and recreation of database.
#
undo_HA(){
  
   [ "$force_base_flag" = "0" -a "$recreate_database_flag" = "0" ] && return 
  
   echologverbose 'Updating oracle files for real hostname...'
   
   current_host=`/usr/bin/hostname`

   # initSunMC.ora
   # No need to check presence of these files as it is already verified
   #
   current_file="$ORACLE_HOME/admin/SunMC/pfile/initSunMC.ora"
   /usr/bin/mv $current_file /tmp/initSunMC.ora.tmp
   old_hostname=`/usr/bin/cat /tmp/initSunMC.ora.tmp | /usr/bin/grep "HOST" | /usr/bin/cut -d= -f10 | /usr/bin/cut -d")" -f1 2> /dev/null  `
   [ -z "$old_hostname" ] && echolog 'Can not find hostname in file:$2' "$current_file" && exit_SunMC "$DATABASE_ERROR"
   /usr/bin/cat /tmp/initSunMC.ora.tmp | /usr/bin/sed s/"HOST=$old_hostname"/"HOST=$current_host"/ > $current_file
   /usr/bin/chmod 444 $current_file
   /usr/bin/chown smcorau:smcorag $current_file
   /usr/bin/rm -f /tmp/initSunMC.ora.tmp
 
   
   # listener.ora
   #
   current_file="$ORACLE_HOME/network/admin/listener.ora"
   /usr/bin/mv $current_file /tmp/listener.ora.tmp
   /usr/bin/cat /tmp/listener.ora.tmp | /usr/bin/sed s/"HOST = $old_hostname"/"HOST = $current_host"/ > $current_file
   /usr/bin/chmod 464 $current_file
   /usr/bin/chown smcorau:smcorag $current_file
   /usr/bin/rm -f /tmp/listener.ora.tmp
   
   # Update tnsnames.ora
   #
   current_file="$ORACLE_HOME/network/admin/tnsnames.ora"
   /usr/bin/mv $current_file /tmp/tnsnames.ora.tmp
   /usr/bin/cat /tmp/tnsnames.ora.tmp | /usr/bin/sed s/"HOST = $old_hostname"/"HOST = $current_host"/ > $current_file
   /usr/bin/chmod 464 $current_file
   /usr/bin/chown smcorau:smcorag $current_file
   /usr/bin/rm -f /tmp/tnsnames.ora.tmp

   # Update dbase.cfgs
   # 
   if [ -f ${VAROPTDIR}/cfg/dbase.cfg ]; then
      /usr/bin/chmod u+w ${VAROPTDIR}/cfg/dbase.cfg
      /usr/bin/mv -f ${VAROPTDIR}/cfg/dbase.cfg ${VAROPTDIR}/cfg/dbase.cfg.HA
      /usr/bin/cat ${VAROPTDIR}/cfg/dbase.cfg.HA | grep -v "host=" >> ${VAROPTDIR}/cfg/dbase.cfg
      /usr/bin/echo  "host=$current_host\n" >> ${VAROPTDIR}/cfg/dbase.cfg
   fi   
   
   if [ -f "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties" ]; then
      [ -f "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties" ] && /usr/bin/mv -f "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties" "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties.HA"
      /usr/bin/cp "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties.HA" /tmp/alternativeservice.properties
      /usr/bin/cat /tmp/alternativeservice.properties | /usr/bin/grep -v "AlternateServiceHost"  > "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties"
      /usr/bin/echo  "#AlternateServiceHost =\n " >> "${VAROPTDIR}/classes/com/sun/symon/base/mgmtservice/alternativeservice.properties"
      /usr/bin/rm -f /tmp/alternativeservice.properties 
   fi
 
   unset current_file current_host old_hostname

}



#
#  Fixes the enterprise and version fields
#
fix_ent_vers() {
    # echo "\nBefore:\n$LINE"
    LINE=`echo $LINE | /usr/bin/sed s/halcyon/sun/g`
    LINE=`echo $LINE | /usr/bin/sed s/'version *= *\"1\.0\"'/'version = \"2.0\"'/`

}

fix_topology_modules() {

    [ -f $VARDIR/topology-modules-d.dat.old ] && /usr/bin/rm $VARDIR/topology-modules-d.dat.old
    if [ -f $VARDIR/topology-modules-d.dat ]; then
        /usr/bin/mv $VARDIR/topology-modules-d.dat $VARDIR/topology-modules-d.dat.old
        SED=/usr/bin/sed

        while read LINE
        do
            module=`echo $LINE | /usr/bin/awk '{print $1}'`
            case $module in
                domain-control)
                    fix_ent_vers
                    LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.domain\.control/prod.sunsymon.agent.modules.domainControl/g`
                    LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.domainControl\"'/`
                    ;;
                topology-license)
                    fix_ent_vers
                    LINE=`echo $LINE | $SED s/primealert\.modules\.localApplication\.topology\.license/prod.sunsymon.agent.modules.topologyLicense/g`
                    LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.topologyLicense\"'/`
                    ;;
                topology*)
                    fix_ent_vers
                    LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.topology/prod.sunsymon.agent.modules.topology/g`
                    LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.topology\"'/`
                    ;;
                discovery)
                    fix_ent_vers
                    LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.discovery/prod.sunsymon.agent.modules.discovery/g`
                    LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.discovery\"'/`
                    ;;
                *)
                    ;;
            esac

            LINE=`echo $LINE | /usr/bin/sed s/'"\; '/'\\\"\; '/g`
            LINE=`echo $LINE | /usr/bin/sed s/'= "'/'= \\\"'/g`
            #  Remove the first \
            LINE=`echo $LINE | /usr/bin/sed s:'\\\'::`
            echo "$LINE" >> $VARDIR/topology-modules-d.dat

        done < "$VARDIR/topology-modules-d.dat.old"

    fi

}

fix_cfgserver_modules() {

    [ -f $VARDIR/cfgserver-modules-d.dat.old ] && /usr/bin/rm $VARDIR/cfgserver-modules-d.dat.old
    if [ -f $VARDIR/cfgserver-modules-d.dat ] ; then
        /usr/bin/mv $VARDIR/cfgserver-modules-d.dat $VARDIR/cfgserver-modules-d.dat.old
        SED=/usr/bin/sed

        while read LINE
        do
            module=`echo $LINE | /usr/bin/awk '{print $1}'`
            case $module in
                cfgserver)
                    fix_ent_vers
                    LINE=`echo $LINE | $SED s/primealert\.modules\.serverSupport\.cfgserver/prod.sunsymon.agent.modules.cfgserver/g`
                    LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.cfgserver\"'/`
                    ;;
                *)
                    ;;
            esac
            LINE=`echo $LINE | /usr/bin/sed s/'"\; '/'\\\"\; '/g`
            LINE=`echo $LINE | /usr/bin/sed s/'= "'/'= \\\"'/g`
            #  Remove the first \
            LINE=`echo $LINE | /usr/bin/sed s:'\\\'::`
            echo "$LINE" >> $VARDIR/cfgserver-modules-d.dat

        done < "$VARDIR/cfgserver-modules-d.dat.old"
    fi
}

fix_trap_modules() {

    return 0

}


fix_event_modules() {

    [ -f $VARDIR/event-modules-d.dat.old ] && /usr/bin/rm $VARDIR/event-modules-d.dat.old
    if [ -f $VARDIR/event-modules-d.dat ] ; then 
        /usr/bin/mv $VARDIR/event-modules-d.dat $VARDIR/event-modules-d.dat.old
        SED=/usr/bin/sed

        while read LINE
        do
            module=`echo $LINE | /usr/bin/awk '{print $1}'`
            case $module in
                eventmgr)
                    fix_ent_vers
                    LINE=`echo $LINE | $SED s/primealert\.modules\.localApplication\.eventmgr/prod.sunsymon.agent.modules.eventmgr/g`
                    LINE=`echo $LINE | $SED s/'location = ""'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.eventmgr\"'/`
                    ;;
                *)
                    ;;
            esac
            LINE=`echo $LINE | /usr/bin/sed s/'"\; '/'\\\"\; '/g`
            LINE=`echo $LINE | /usr/bin/sed s/'= "'/'= \\\"'/g`
            #  Remove the first \
            LINE=`echo $LINE | /usr/bin/sed s:'\\\'::`
            echo "$LINE" >> $VARDIR/event-modules-d.dat

        done < "$VARDIR/event-modules-d.dat.old"

    fi
}

fix_cstservice_modules() {

    return 0

}

fix_metadata_modules() {

    [ -f $VARDIR/metadata-modules-d.dat.old ] && /usr/bin/rm $VARDIR/metadata-modules-d.dat.old
    if [ -f $VARDIR/metadata-modules-d.dat ]; then

        /usr/bin/mv $VARDIR/metadata-modules-d.dat $VARDIR/metadata-modules-d.dat.old
        SED=/usr/bin/sed

        while read LINE ; do
           module=`echo $LINE | /usr/bin/awk '{print $1}'`
           case $module in

              datalog-registry)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.localApplication.datalog.registry/prod.sunsymon.agent.modules.datalogRegistry/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.datalogRegistry\"'/`
                 ;;
              dirmon*)
                fix_ent_vers
                LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.dirmon\"'/`
                LINE=`echo $LINE | $SED s/'location = ""'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.dirmon\"'/`
                ;;
              filemon*)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.operatingSystem.filemon/prod.sunsymon.agent.modules.filemon/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.filemon\"'/`
                ;;
              fscan*)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.localApplication.fscan/prod.sunsymon.agent.modules.fscan/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.fscan\"'/`
                ;;
              hp-jetdirect*)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.remoteSystem.hp.jetdirect/prod.sunsymon.agent.modules.hpJetdirect/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.hpJetdirect\"'/`
                 ;;
              nfsmon*)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.operatingSystem.nfsmon/prod.sunsymon.agent.modules.nfsmon/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.nfsmon\"'/`
                 ;;
              nfsstat)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.operatingSystem.nfsstat/prod.sunsymon.agent.modules.nfsstat/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.\"'/`
                 ;;
              print-spool*)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.localApplication.print.spool/prod.sunsymon.agent.modules.printSpool/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.printSpool\"'/`
                 ;;
              process-table*)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/primealert.modules.localApplication.process.table/prod.sunsymon.agent.modules.processTable/`
                 LINE=`echo $LINE | $SED s/'location = \"\"'/'location = \".iso.org.dod.internet.private.enterprises.sun.prod.sunsymon.agent.modules.processTable\"'/`
                 ;;
              kernel-reader)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/operatingSystem.kernel.reader/kernelReader/`
                 ;;
               process-details)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/operatingSystem.process.details/processDetails/`
                 ;;
              health-monitor)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/localApplication.health.monitor/healthMonitor/`
                 ;;
              dr)
                 fix_ent_vers
                 LINE=`echo $LINE | $SED s/localApplication.dr/dr/`
                 ;;
              *)
                 ;;
           esac
           LINE=`echo $LINE | /usr/bin/sed s/'"\; '/'\\\"\; '/g`
           LINE=`echo $LINE | /usr/bin/sed s/'= "'/'= \\\"'/g`
           #  Remove the first \
           LINE=`echo $LINE | /usr/bin/sed s:'\\\'::`
           echo "$LINE" >> $VARDIR/metadata-modules-d.dat
     
         done < "$VARDIR/metadata-modules-d.dat.old"

    fi
  
}





# Returns : - Returns name of layer.
# $1 - LAYER keys
get_layer_name () {   

   [ -z "$1" ] && /usr/bin/echo "" && return 0
   tmp_layer_name=`/usr/bin/echo "$1" | /usr/bin/sed "s/LAYER.//g" 2> /dev/null`
   tmp_layer_name=`/usr/bin/echo "$tmp_layer_name" | /usr/bin/sed "s/ /,/g" 2> /dev/null`
   /usr/bin/echo "$tmp_layer_name"
   unset tmp_layer_name
   return 0
}

#
# Method to correct the dtable.toe file. This method will replace all
# host2ip command by resolveHostName.
#
correctDtableToeFile () {
    TOEFILENAME="$ESDIR/cfg/dtable.toe"
    if [ ! -f $TOEFILENAME ] ; then
        return
    fi
    linecount=0
    linecount=`/usr/bin/cat $TOEFILENAME | /usr/bin/grep -v "^#" | /usr/bin/grep -c host2ip`
    if [ $linecount -eq 0 ] ; then
        return
    fi
    #
    # It seems the file has host2ip, so replace it with resolveHostName
    #
    /usr/bin/ed -s $TOEFILENAME > /dev/null 2>&1 << EOF
1,$ s/\[[ 	]*host2ip/\[ resolveHostName/
w
q
EOF
}

# This function should be called only after core setup is done and after all addon
# setups are done. Do not call this function before the addon setups are done.
# This function should not be called with es-setup -b option as the -b option
# does ONLY base setup without calling the addon setup.

# As the name suggests, this function should be the last thing that is done before
# the setup prompts the user to start SunMC server components.

do_post_setup_processing () {

    set_inst_flags

    # install_on_cluster is set by a call to get_HA_information in the es-setup script

    [ $install_on_cluster -eq 1 ] && update_for_logical_hostname
    [ $install_on_cluster -eq 0 ] && start_SunMC

    # Cleanup migration directories if they are empty (does nothing if the
    # directory is already removed)
    rmdir_if_empty $ESDIR/upgrade
}



#
# Setup old data directory for migration
#
setup_olddata_dir() {
    if [ -d "$VAROPTDIR/upgrade/cfg" ]; then
	OLDDATADIR="$VAROPTDIR/upgrade"
    elif [ -d "$VAROPTDIR/2x/cfg" ]; then
	OLDDATADIR="$VAROPTDIR/2x"
    else
	OLDDATADIR=""
    fi

    export OLDDATADIR
}


#
# Check if the setup conditions satisfied when run the "es-setup -k" command.
# If not, exit the setup process
#
check_keepseed_conditions() {
    if [ "$OLDDATADIR" != "" ]; then
	cfgdir="$OLDDATADIR/cfg"
    else
	cfgdir="$VARDIR"
    fi

    if [ $no_server -eq 0 ]; then
	#
	# installed server
	#

	if [ ! -f $cfgdir/metadata-engine-d.dat ]; then
	    echolog 'Can not run es-setup with -k option because $cfgdir/metadata-engine-d.dat file does not exist.'
	    exit_SunMC_setup "$SERVER_SETUP_ERROR"
	fi

    elif [ $no_agent -eq 0 ]; then
	#
	# installed agent
	#

	if [ ! -f $cfgdir/agent-engine-d.dat ]; then
	    echolog 'Can not run es-setup with the -k option because $cfgdir/agent-engine-d.dat file does not exist.'
	    exit_SunMC_setup "$AGENT_SETUP_ERROR"
	fi
    fi
}

#
# Migrate 3.0/3.5 security related files when run "es-setup -k"
#
migrate_30_security_files() {
    set_xput

    #
    # always include agent and platform components because they must be
    # installed for 3.5 server
    #
    components="agent platform"

    if [ $no_server -eq 0 ]; then
	components=${components}" metadata topology cfgserver event cstservice trap"
    fi

    [ -z "$SNMPV1_STRING" ] && SNMPV1_STRING="public"

    COMP=""
    for COMP in $components
    do
        if [ ! -f ${VARDIR}/${COMP}-engine-d.dat ]; then
	    /usr/bin/cp ${OLDDATADIR}/cfg/${COMP}-engine-d.dat ${VARDIR}/${COMP}-engine-d.dat
	    /usr/bin/cp ${OLDDATADIR}/cfg/${COMP}-usmusertbl-d.dat ${VARDIR}/${COMP}-usmusertbl-d.dat
	    #
	    # The file usmuser-d.dat will not exist for a component 
	    # that wasn't started so check before proceeding. Also
	    # ideally read the file name for acls from ${COMP}-usmuser-d.dat
	    # if not use ${COMP}-usmaclgrps-d.dat
	    #
	    if [ -f ${OLDDATADIR}/cfg/${COMP}-usmuser-d.dat ]; then
	    	$CMD_CP ${OLDDATADIR}/cfg/${COMP}-usmuser-d.dat ${VARDIR}/${COMP}-usmuser-d.dat
		sfile_name=`$XGET ${VARDIR}/${COMP}-usmuser-d.dat subsyncfiles`
	    	if [ -n "$sfile_name" ]; then
			$CMD_CP ${OLDDATADIR}/cfg/${sfile_name} ${VARDIR}/${sfile_name}
	    	elif [ -f ${OLDDATADIR}/cfg/${COMP}-usmaclgrps-d.dat ]; then
			$CMD_CP ${OLDDATADIR}/cfg/${COMP}-usmaclgrps-d.dat ${VARDIR}/${COMP}-usmaclgrps-d.dat
	    	fi
	    fi
        fi

	#
	# 3.0 has no community data, so generate new one for it.
	# 3.5 has it, just copy the old one if new file is not exist.
	#
	if [ -f ${OLDDATADIR}/cfg/${COMP}-community.dat -a ! -f ${VARDIR}/${COMP}-community.dat ]; then
	    /usr/bin/cp ${OLDDATADIR}/cfg/${COMP}-community.dat ${VARDIR}/${COMP}-community.dat
	else
	    /usr/bin/touch "${VARDIR}/${COMP}-community.dat"
	    configure_community_string_file ${COMP}
	fi
    done

    #
    # copy other security files
    #
    if [ $no_server -eq 0 ]; then
	/usr/bin/cp ${OLDDATADIR}/cfg/server-global-keys.x ${VARDIR}/server-global-keys.x
	/usr/bin/cp ${OLDDATADIR}/cfg/auth-suppl.dat ${VARDIR}/auth-suppl.dat
	/usr/bin/cp ${OLDDATADIR}/cfg/cfgserver-users.dat ${VARDIR}/cfgserver-users.dat
	/usr/bin/cp ${OLDDATADIR}/cfg/config-id.dat ${VARDIR}/config-id.dat
	/usr/bin/cp ${OLDDATADIR}/cfg/config-diffs.dat ${VARDIR}/config-diffs.dat
    fi
}

# Just take a backup of the existing key and cfgserver-engines file
# Bugfix 5010497
backup_existing_key () {
    if [ -f ${VARDIR}/auth-suppl.dat ]; then
        $CMD_RM -f ${VARDIR}/auth-suppl.dat.org
        $CMD_CP ${VARDIR}/auth-suppl.dat ${VARDIR}/auth-suppl.dat.org
        # make sure it has rw only for root.
        $CMD_CHMOD 600 ${VARDIR}/auth-suppl.dat.org
    fi
    if [ -f ${VARDIR}/cfgserver-engines.dat ]; then
        $CMD_RM -f ${VARDIR}/cfgserver-engines.dat.org
        $CMD_CP ${VARDIR}/cfgserver-engines.dat ${VARDIR}/cfgserver-engines.dat.org
        # make sure it has rw only for root.
        $CMD_CHMOD 600 ${VARDIR}/cfgserver-engines.dat.org
    fi
}


# Decide whether or not to delete cfg server engines file.
#                         Seed Changed         Seed did not change
# Preserver Data          Delete               Restore Old
# Do not Preserve data    Delete               Delete
# Bugfix 5010497

retain_cfgserver_engines () {
    
    key_changed=1

    if [ -f ${VARDIR}/auth-suppl.dat.org -a -f ${VARDIR}/auth-suppl.dat ]; then
        # We can compare
        set_xput
        old_key=`$XGET ${VARDIR}/auth-suppl.dat.org authkey\(esmaster\) 2> /dev/null`
        new_key=`$XGET ${VARDIR}/auth-suppl.dat authkey\(esmaster\) 2> /dev/null`
        if [ "$old_key" = "$new_key" ]; then
            key_changed=0
        fi
    fi

    # If the seed was changed. Or the user said NO to save data
    # the following block will not do anything
    # and effectively, the RM statement in db-common.sh will 
    # delete the file which is as per the expected behavior.

    if [ $key_changed -eq 0 ]; then
        # The seed has not changed.
        # we need to preserve cfgserver-engines.dat file if user says so
        if [ "$CORE_DATA_PRESERVED" = "1" ]; then
                
            if [ -f ${VARDIR}/cfgserver-engines.dat.org ]; then
                #probably the file was generated. delete this.
                [ -f ${VARDIR}/cfgserver-engines.dat ] && $CMD_RM ${VARDIR}/cfgserver-engines.dat
                # restore the old file.
                $CMD_MV ${VARDIR}/cfgserver-engines.dat.org ${VARDIR}/cfgserver-engines.dat
                # make sure it has rw only for root.
                $CMD_CHMOD 600 ${VARDIR}/cfgserver-engines.dat
            fi
        fi
    fi
}

#
# Migrate 3.0/3.5 platform agent instances
#
migrate_30_platform_instances() {
    set_xput
    CFGFILE=$CFGDIR/platform-instances.dat

    #
    # if there is no platform-instances file, just return OK
    #
    if [ ! -f $CFGFILE ] ; then
	return 0
    fi

    /usr/bin/chmod 600 $CFGFILE

    #
    # check if the plaftform instances exist
    #
    list_of_instances=""
    list_of_instances=`$XGET $CFGFILE ControlBlock.instances`
    list_of_instances=`/usr/bin/echo $list_of_instances | /usr/bin/sed -e "s/,/ /g"`
    if [ -z "$list_of_instances" ] ; then
	return 0
    fi

    if [ ! -f "$VARDIR/user-config.x" ] ; then
	/usr/bin/cp -f "$BASEDIR"/base/cfg/user-config.x "$VARDIR/user-config.x"
    fi

    OLDCFGFILE=${OLDDATADIR}/cfg/domain-config.x

    ServerName=`$XGET ${VARDIR}/domain-config.x agent.agentServer`

    #
    # migrate all platform instances
    #
    INSTANCE=""
    for INSTANCE in $list_of_instances
    do
	#
	# Update user-config.x file
	# First remove the instance from the user-config.x
	#
	/usr/bin/sed -e "/^#Instance $INSTANCE Start/,/^#Instance $INSTANCE End/d" "$VARDIR/user-config.x" > /tmp/user-config.x.${PID}
	/usr/bin/mv /tmp/user-config.x.${PID} "$VARDIR/user-config.x"

	echo "#Instance $INSTANCE Start" >> "$VARDIR/user-config.x"
	echo "$INSTANCE = { [ inherit security ]" >> "$VARDIR/user-config.x"
	echo "    }" >> "$VARDIR"/user-config.x
	echo "#Instance $INSTANCENAME End" >> "$VARDIR"/user-config.x

	#
	# Update domain-config.x file
	#

	#
	# Use new server name, may change sometime
	#
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.${INSTANCE}Server "$ServerName"

	old_port=`$XGET $OLDCFGFILE ${INSTANCE}.snmpPort`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.snmpPort "$old_port"

	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.logicalAddressMode "ip"

	old_desc=`$XGET $OLDCFGFILE ${INSTANCE}.description`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.description "$old_desc"

	old_activeChannels=`$XGET $OLDCFGFILE ${INSTANCE}.activeChannels`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.activeChannels "$old_activeChannels"

	old_defaultOutput=`$XGET $OLDCFGFILE ${INSTANCE}.defaultOutput`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.defaultOutput "$old_defaultOutput"

	old_statusOutput=`$XGET $OLDCFGFILE ${INSTANCE}.statusOutput`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.statusOutput "$old_statusOutput"

	old_syslogOutput=`$XGET $OLDCFGFILE ${INSTANCE}.syslogOutput`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.syslogOutput "$old_syslogOutput"

	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.auditOutput  "clog://localhost/../log/${INSTANCE}Audit.log;lines=1000;width=200;flags=rw+;mode=644"

	old_moduleFile=`$XGET $OLDCFGFILE ${INSTANCE}.moduleFile`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.moduleFile "$old_moduleFile"

	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.scheduleFile "value:${INSTANCE}-schedule.dat"

	old_randomSeed=`$XGET $OLDCFGFILE ${INSTANCE}.randomSeed`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.randomSeed "$old_randomSeed"

	old_niceValue=`$XGET $OLDCFGFILE ${INSTANCE}.niceValue`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.niceValue "$old_niceValue"

	old_numFileLimit=`$XGET $OLDCFGFILE ${INSTANCE}.numFileLimit`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.numFileLimit "$old_numFileLimit"

	old_usmUserFiles=`$XGET $OLDCFGFILE ${INSTANCE}.usmUserFiles`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.usmUserFiles "$old_usmUserFiles"

	old_usmAclFile=`$XGET $OLDCFGFILE ${INSTANCE}.usmAclFile`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.usmAclFile "$old_usmAclFile"

	old_agentStatsFile=`$XGET $OLDCFGFILE ${INSTANCE}.agentStatsFile`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.agentStatsFile "$old_agentStatsFile"

	old_mib2SystemFile=`$XGET $OLDCFGFILE ${INSTANCE}.mib2SystemFile`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.mib2SystemFile "$old_mib2SystemFile"

	old_enterprise=`$XGET $OLDCFGFILE ${INSTANCE}.enterprise`
	$XPUT ${VARDIR}/domain-config.x ${INSTANCE}.enterprise "$old_enterprise"

	#
	# Create new base-$INSTANCE.x files
	#
	/usr/bin/cat $BASEDIR/base/cfg/base-platform.x | /usr/bin/sed -e "s/platform/$INSTANCE/g" > $CFGDIR/base-${INSTANCE}.x
	/usr/bin/chmod 600 $CFGDIR/base-${INSTANCE}.x

	/usr/bin/cp ${BASEDIR}/base/cfg/platform-usmuser-d.dat ${VARDIR}/${INSTANCE}-usmuser-d.dat
	/usr/bin/chmod 600 ${VARDIR}/${INSTANCE}-usmuser-d.dat

	/usr/bin/cp ${BASEDIR}/base/cfg/platform-usmaclgrps-d.dat ${VARDIR}/${INSTANCE}-usmaclgrps-d.dat
	/usr/bin/chmod 600 ${VARDIR}/${INSTANCE}-usmaclgrps-d.dat

	#
	# If schedule file exist in the old repository, just copy it;
	# otherwise generate new files.
	#
	if [ -f ${OLDDATADIR}/cfg/${INSTANCE}-schedule.dat ]; then
	    /usr/bin/cp ${OLDDATADIR}/cfg/${INSTANCE}-schedule.dat ${VARDIR}/${INSTANCE}-schedule.dat
	else
	    /usr/bin/cp ${BASEDIR}/base/cfg/platform-schedule.dat  ${VARDIR}/${INSTANCE}-schedule.dat
	fi

	/usr/bin/chmod 600  ${VARDIR}/${INSTANCE}-schedule.dat

	if [ -f ${VARDIR}/${INSTANCE}-acls-d.dat ]; then
	    /usr/bin/chmod 600 ${VARDIR}/${INSTANCE}-acls-d.dat
	fi

	if [ -f ${VARDIR}/${INSTANCE}-modules-d.dat ]; then
	    /usr/bin/chmod 600 ${VARDIR}/${INSTANCE}-modules-d.dat
	fi

	if [ -f ${VARDIR}/${INSTANCE}-snmp-cache-d.dat ]; then
	    /usr/bin/chmod 600 ${VARDIR}/${INSTANCE}-snmp-cache-d.dat
	fi

	#
	# Process security related files
	# If run "es-setup -k", use old security files 
	# else generate new files
	#
	[ -z "$SNMPV1_STRING" ] && SNMPV1_STRING="public"
	if [ "$generate_security_keys" = "1" ]; then
	    $BASEDIR/base/sbin/base-usm-seed.sh -s "$seed" -v1 "$SNMPV1_STRING" -c $INSTANCE
	    /usr/bin/touch "${VARDIR}/${INSTANCE}-community.dat"
	    configure_community_string_file ${INSTANCE}

            _migrate_comm_str ${INSTANCE}
	else
            if [ ! -f ${VARDIR}/${INSTANCE}-engine-d.dat ]; then
                /usr/bin/cp ${OLDDATADIR}/cfg/${INSTANCE}-engine-d.dat ${VARDIR}/${INSTANCE}-engine-d.dat
                /usr/bin/cp ${OLDDATADIR}/cfg/${INSTANCE}-usmusertbl-d.dat ${VARDIR}/${INSTANCE}-usmusertbl-d.dat
	        #
	        # The file usmuser-d.dat will not exist for a component 
	        # that wasn't started so check before proceeding. Also
	        # ideally read the file name for acls from ${COMP}-usmuser-d.dat
	        # if not use ${COMP}-usmaclgrps-d.dat
	    	#
	    	if [ -f ${OLDDATADIR}/cfg/${INSTANCE}-usmuser-d.dat ]; then
		    $CMD_CP ${OLDDATADIR}/cfg/${INSTANCE}-usmuser-d.dat ${VARDIR}/${INSTANCE}-usmuser-d.dat
		    sfile_name=`$XGET ${VARDIR}/${INSTANCE}-usmuser-d.dat subsyncfiles`
		    if [ -n "$sfile_name" ]; then
			$CMD_CP ${OLDDATADIR}/cfg/${sfile_name} ${VARDIR}/${sfile_name}
		    elif [ -f ${OLDDATADIR}/cfg/${INSTANCE}-usmaclgrps-d.dat ]; then
			$CMD_CP ${OLDDATADIR}/cfg/${INSTANCE}-usmaclgrps-d.dat ${VARDIR}/${INSTANCE}-usmaclgrps-d.dat
		    fi
	    	fi
            fi

	    #
	    # 3.0 has no community data, so generate new one for it.
	    # 3.5 has it, just copy the old one if new file is not exist.
	    #
	    if [ -f ${OLDDATADIR}/cfg/${INSTANCE}-community.dat -a ! -f ${VARDIR}/${INSTANCE}-community.dat ]; then
	        /usr/bin/cp ${OLDDATADIR}/cfg/${INSTANCE}-community.dat ${VARDIR}/${INSTANCE}-community.dat
		/usr/bin/chmod 600 ${VARDIR}/${INSTANCE}-community.dat
	    else
		/usr/bin/touch "${VARDIR}/${INSTANCE}-community.dat"
		configure_community_string_file ${INSTANCE}
	    fi
	fi
    done
}

# Called internally by migrate_agent_cfgfiles
# $OLDCFG=old cfg dir, $CFGDIR=current cfg dir
migrate_domain_config () {
    set_xput

    # Copy the following keys from old domain-config.x:
    # activeChannels, SNMPv1, SNMPv2c
    for component in agent trap event platform metadata topology cfgserver cstservice ; do
        for key in activeChannels SNMPv1 SNMPv2c ; do
            value=`$XGET $OLDCFG/domain-config.x ${component}.${key}`
            if [ ! -z "$value" ] ; then
                $XPUT $CFGDIR/domain-config.x ${component}.${key} "$value"
            fi
        done
    done

    # Copy maxPort and minPort from topology, probe and server
    for component in topology probe server ; do
        for key in minPort maxPort ; do
            value=`$XGET $OLDCFG/domain-config.x ${component}.${key}`
            if [ ! -z "$value" ] ; then
                $XPUT $CFGDIR/domain-config.x ${component}.${key} "$value"
            fi
        done
    done

    # Topology-specific stuff
    for key in agentStatusInterval snmpPingInterval icmpPingInterval ; do
        value=`$XGET $OLDCFG/domain-config.x topology.${key}`
        if [ ! -z "$value" ] ; then
            $XPUT $CFGDIR/domain-config.x topology.${key} "$value"
        fi
    done
}

migrate_agent_cfgfiles () {

    # domain-config.x
    if [ -f $OLDCFG/domain-config.x ] ; then
        echolog 'Merging file: $2' "domain-config.x"
        migrate_domain_config
    fi

    # base-modules-d.dat
    if [ -f $OLDCFG/base-modules-d.dat ] ; then
        echolog 'Merging base-modules-d.dat'
	cp ${OLDCFG}/base-modules-d.dat ${CFGDIR}/base-modules-d.dat
        /usr/bin/grep '^hdreg =' $CFGDIR/base-modules-d.dat > /dev/null 2>&1
        if [ $? -ne 0 ] ; then
            /usr/bin/grep 'hdreg =' ${BASEDIR}/base/cfg/base-modules-d.dat >> ${CFGDIR}/base-modules-d.dat
        fi

        /usr/bin/grep '^mcp =' $CFGDIR/base-modules-d.dat > /dev/null 2>&1
        if [ $? -ne 0 ] ; then
            /usr/bin/grep 'mcp =' ${BASEDIR}/base/cfg/base-modules-d.dat >> ${CFGDIR}/base-modules-d.dat
        fi
        /usr/bin/chmod 600 $CFGDIR/base-modules-d.dat
    fi

    # logview-acl.dat --> logview.dat
    if [ -f $OLDCFG/logview-acl.dat ] ; then
        echolog 'Migrating file: $2' "logview-acl.dat"
        prevlogviewline=`/usr/bin/grep fileList $OLDCFG/logview-acl.dat | /usr/bin/sed -e 's/^[^=]*fileList[ ]*=[ ]*"//' -e 's/"[ ]*$//' `

        if [ -f $CFGDIR/logview.dat ] ; then
            # Extract existing value
            newlogviewline=`/usr/bin/grep value:fileList $CFGDIR/logview.dat | /usr/bin/sed -e 's/^[^=]*value:fileList[ ]*=[ ]*"//' -e 's/"[ ]*$//' `
        fi

        /bin/cat > $CFGDIR/logview.dat <<EOF
logviewacl = {
	value:fileList = "$prevlogviewline $newlogviewline"
}
EOF

    fi

    # Migrate $ESDIR/bin
    if [ -d $OLDDATADIR/bin ] ; then
        for file in $OLDDATADIR/bin/* ; do
            filename=`/usr/bin/basename $file`
            if [ ! -f $BINDIR/$filename ] ; then
                echolog 'Migrating file: $2' "$BINDIR/$filename"
                /usr/bin/mv $file $BINDIR/$filename
            else
                /usr/bin/mv $file $BINDIR/$filename.OLD
            fi
        done
    fi
}

migrate_server_cfgfiles () {

    # javaserver.properties
    JSFILE="javaserver.properties"
    if [ -f $OLDCFG/$JSFILE ] ; then
        echolog 'Migrating file: $2' "$JSFILE"
        /usr/bin/cp $CFGDIR/$JSFILE /tmp/$JSFILE

        CMD="/^MinPort/d; /^MaxPort/d; /^TopologyMode/d; /^ *PublicPrivProtocol/d; /^ *snmp_PrivatePrivProtocol/d; /^ *snmp_SecurityLevel/d; /^ *snmppublic_SecurityLevel/d; /^ *AutoNegotiate/d; /^ *PrivReqOid/d"

        /usr/bin/sed "$CMD" $OLDCFG/$JSFILE > $CFGDIR/$JSFILE
        /usr/bin/cat >> $CFGDIR/$JSFILE <<EOF
MinPort = @server_MinPort
MaxPort = @server_MaxPort
TopologyMode = @topology_LogicalAddressMode
EOF

        # copy snmp privacy attributes
        /usr/bin/egrep "^ *PrivReqOid" /tmp/$JSFILE >> $CFGDIR/$JSFILE
        /usr/bin/egrep "^ *AutoNegotiate" /tmp/$JSFILE >> $CFGDIR/$JSFILE
        /usr/bin/egrep "^ *PublicPrivProtocol" /tmp/$JSFILE >> $CFGDIR/$JSFILE
        /usr/bin/egrep "^ *snmp_PrivatePrivProtocol" /tmp/$JSFILE >> $CFGDIR/$JSFILE
        /usr/bin/egrep "^ *snmp_SecurityLevel" /tmp/$JSFILE >> $CFGDIR/$JSFILE
        /usr/bin/egrep "^ *snmppublic_SecurityLevel" /tmp/$JSFILE >> $CFGDIR/$JSFILE

        /usr/bin/chmod 600 $CFGDIR/$JSFILE
        /usr/bin/rm /tmp/$JSFILE
    fi

    # TBD: merge discovery-j.x


    # esusers
    if [ -f $OLDCFG/esusers ] ; then
        echolog 'Migrating file: $2' "esusers"
        /usr/bin/mv $CFGDIR/esusers $CFGDIR/esusers.orig
        /usr/bin/cat $CFGDIR/esusers.orig $OLDCFG/esusers | /usr/bin/sort | /usr/bin/uniq > $CFGDIR/esusers
    fi


    # Fix OID hierarchy in server component module files.
    # NOTE: this should be done last in this function.
    #
    # This is mainly for 2.x migration; but we're always doing it here so
    # that we'll weed out any remaining obsolete OIDs still lying around.
    # For modules that have already been fixed (3.5 server components) this
    # is a no-op.
    VARDIR=$CFGDIR
    fix_topology_modules
    fix_cfgserver_modules
    fix_trap_modules
    fix_event_modules
    fix_cstservice_modules
    fix_metadata_modules
}

#
# Migrate snmpv1 community string.
# This is only happened for 3.5 to 3.5 migration and not run 'es-setup -k'
#
migrate_community_string()
{
    # community file has migrated so we needn't merge the string
    #
    [ "$generate_security_keys" = "0" ] && return

    components="agent platform"

    if [ $no_server -eq 0 ]; then
	components=${components}" metadata topology cfgserver event cstservice trap"
    fi

    COMP=""
    for COMP in $components
    do
        _migrate_comm_str ${COMP}
    done
}

# Migrate community string for a component
#
_migrate_comm_str() {
    set_xput
    if [ -f ${OLDDATADIR}/cfg/${1}-community.dat ]; then
        # the old community string depends on the merged flag
        #
        merged=`$XGET ${OLDDATADIR}/cfg/${1}-community.dat merged`
        if [ "$merged" = "-1" ]; then
            old=`$XGET ${OLDDATADIR}/cfg/${1}-community.dat new`
        else
            old=`$XGET ${OLDDATADIR}/cfg/${1}-community.dat old`
        fi
    
        [ -z "$old" ] && old="public"

        # if old string is "public" and there is no new $1-community.dat 
        # file, that means the new string is also "public", and we do nothing.
        #

        if [ -f ${VARDIR}/${1}-community.dat ]; then
            $XPUT ${VARDIR}/${1}-community.dat old $old
        elif [ "$old" != "public" ]; then
            $XPUT ${VARDIR}/${1}-community.dat new "public"
            $XPUT ${VARDIR}/${1}-community.dat old $old
        fi
    fi
}

#
# Check the resp file and export MIGRATE_DATA variable for addon only
# setup. MIGRATE_DATA=1 if IMPORT_PREVIOUS_DATA tag is set to 1. MIGRATE_DATA=0
# if IMPORT_PREVIOUS_DATA tag is set to 0. MIGRATE_DATA will not be defined
# if IMPORT_PREVIOUS_DATA tag is not specified in the resp file.
#
export_migrate_data () {
    migratevalue=`getAutoConfig IMPORT_PREVIOUS_DATA`
    if [ -n "$migratevalue" ]; then
        if [ "$migratevalue" = "0" ] ; then
            MIGRATE_DATA=0
            export MIGRATE_DATA
        elif [ "$migratevalue" = "1" ] ; then
            MIGRATE_DATA=1
            export MIGRATE_DATA
        fi
    fi
}

