#!/bin/sh
# Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
# pragma ident  "@(#)es-config	1.41 05/03/16 Sun Microsystems"

    PROGNAME=$0
    PREV_DIR=`/usr/bin/pwd`
    SCRIPT_DIR=`/usr/bin/dirname $PROGNAME`
    TOOLS_DIR=${SCRIPT_DIR}/../lib/sbin
    PATH="$PATH:${SCRIPT_DIR}:${TOOLS_DIR}"
#
#
#
# External Files:
# (All placed in $TOOLS_DIR)
#
# script-errors.sh         : Error codes returned by all functions
# es-common.sh             : Common functions
#
# Diagnostics:
# Exit Status: 
#	1 - Fail
#	0 - All available ports configured correctly
#
#                                 
#   Logs:
#        install log    : /var/opt/SUNWsymon/install/latest_ports.$TIMESTAMP.$$
# 
# Temporary files:
#   -    None
#
# Source external files:
#
[ ! -x "${SCRIPT_DIR}/es-common.sh" ] && exit 1 
[ ! -x "${TOOLS_DIR}/script-errors.sh" ] && exit 1 
[ ! -x "${TOOLS_DIR}/db-common.sh" ] && exit 1 
[ ! -x "${TOOLS_DIR}/setup-functions.sh" ] && exit 1 

. ${SCRIPT_DIR}/es-common.sh
. ${TOOLS_DIR}/script-errors.sh
. ${TOOLS_DIR}/db-common.sh # This is required to stop sunmc database.
. ${TOOLS_DIR}/setup-functions.sh
[ -r ${SCRIPT_DIR}/es-keys.sh ] && . ${SCRIPT_DIR}/es-keys.sh

# >> BEGIN functions used by this script >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #

# Prints usage for es-config
# 
print_script_usage () {

    /usr/bin/echo ""
    /usr/bin/gettext 'Sun Management Center 3.5 Update 1 post setup configuration utility.\n'
    /usr/bin/echo ""
    eval /usr/bin/echo "\"`/usr/bin/gettext  'Usage: $PROGNAME [ -Adhmnr ] [ -p sunmc_component ] [  -c sunmc_component:channel ] [ -P MinPort:MaxPort ]\nWhere the options represent:\n'`\""
    /usr/bin/gettext ' Default : Displays all ports occupied by Sun Management Center 3.5 Update 1 base product.\n'
    /usr/bin/gettext ' -A      : Configures all ports.\n'
    /usr/bin/gettext ' -P      : Configures port range to be used for probe mechanism to execute\n           adhoc commands for communication between server and agent.\n           You must configure this to support firewall between server and agent.\n           Valid port numbers are 1100-65535.\n'
    /usr/bin/gettext ' -d      : Restores all ports to a default value.\n'
    /usr/bin/gettext ' -h      : Prints usage.\n'
    /usr/bin/gettext ' -p <sunmc_component> : Configures port to be used by <sunmc_component>.\n           Valid <sunmc_component> are:\n           topology, cfgserver, event, cstservice, trap, metadata,\n           agent, grouping, HTTP, HTTPS, rmi, platform and platform_instances.\n'
    /usr/bin/gettext ' -c <sunmc_component:channel> : Enable/Disable various channels being logged.\n           Valid <sunmc_component> for which channels can be controlled are:\n           topology, cfgserver, event, cstservice, trap, metadata,\n           agent, rmi, platform and platform_instances.\n           Valid <channel> are:\n           debug, info, error, status, history, syslog, warning,\n           eventhistory, trace, trap, audit, and attributeAudit.\n'
    /usr/bin/gettext ' -m      : Configures Module Configuration Propagation.\n'
    /usr/bin/gettext ' -n      : Enable Network Address Translation \(NAT\) support.\n'
    /usr/bin/gettext ' -r      : Regenerate security keys and enable or disable\n           encrypted SNMP communication.\n'
    /usr/bin/gettext ' -a <option> : Setup database in archivelog mode or noarchivelog mode.\n           Accepts <enable> and <disable> options.\n'
	exit 1

}

# invoke the functions based on user supplied options
#
#
process_script_options () {

   sunmc_component="agent"
   configure_all_ports_flag=0
   configure_single_port_flag=0
   configure_port_range_flag=0
   configure_mcp_flag=0
   configure_nat_flag=0
   stop_server_flag=0
   stop_agent_flag=0
   restore_default_ports_flag=0
   reseed_comps_flag=0
   configure_channels=0
   quite_flag=0
   sec_file_flag=0
   config_db_flag=0

   # User will be prompted for re-seeding ( agent components only )
   # based on following three variables.
   # Tye : Once set - Always reset type
   #
   reseeding_required=0
   port_changed=0
   ip_changed=0
   configure_archivelog=0
 
   num_comp=0
   if [ ! -z "$1" ]; then
      /usr/bin/echo "$@" | /usr/bin/grep "-" > /dev/null 2>&1
      [ $? -eq 1 ] && print_script_usage && exit "$ARGUMENTS_ERROR"
   
      while getopts AP:c:dhmnorp:a:qf: OPT
      do
         case $OPT in

            A)  configure_all_ports_flag=1
                num_comp=`/usr/bin/expr $num_comp + 1`
                stop_server_flag=1
                stop_agent_flag=1
            	;;
            a)
                option="$OPTARG"
                if [ "$option" = "enable" -o "$option" = "disable" ]; then
                   configure_archivelog=1
                   return
                else
                   print_script_usage
                fi
                ;;

            P)	
                num_comp=`/usr/bin/expr $num_comp + 1`
                configure_port_range_flag=1
                port_range="$OPTARG"
                MaxPort=`/usr/bin/echo "$port_range" | /usr/bin/cut -f2 -d":" 2> /dev/null `
                MaxPort=`/usr/bin/echo $MaxPort 2> /dev/null `
                MinPort=`/usr/bin/echo "$port_range" | /usr/bin/cut -f1 -d: 2> /dev/null `
                MinPort=`/usr/bin/echo $MinPort 2> /dev/null `
                stop_server_flag=1
                stop_agent_flag=1
                ;;
            o)
                num_comp=`/usr/bin/expr $num_comp + 1`
       		config_db_flag=1
		stop_server_flag=1
		stop_agent_flag=1
		;;

            c)
                #num_comp=`/usr/bin/expr $num_comp + 1`
                sunmc_component="$OPTARG"
                configure_channels=1
                ;;

            h)  
                num_comp=`/usr/bin/expr $num_comp + 1`
                print_script_usage
                exit 0
                ;;

            p)	
                sunmc_port_component="$OPTARG"
                num_comp=`/usr/bin/expr $num_comp + 1`
                configure_single_port_flag=1
                /usr/bin/echo "trap event topology cfgserver cstservice metadata grouping rmi HTTP HTTPS" | /usr/bin/grep -w "$sunmc_port_component" > /dev/null
                if [ $? -eq 0 ]; then
                   stop_server_flag=1
                else
                   stop_agent_flag=1
                fi
                ;;

            d)  num_comp=`/usr/bin/expr $num_comp + 1`
                restore_default_ports_flag=1
                stop_server_flag=1
                stop_agent_flag=1
                ;;
            m)
                #num_comp=`/usr/bin/expr $num_comp + 1`
                configure_mcp_flag=1
                stop_agent_flag=1
                ;;
            n)  
                #num_comp=`/usr/bin/expr $num_comp + 1`
                configure_nat_flag=1
                stop_server_flag=1
                stop_agent_flag=1
                ;;
            r)  #num_comp=`/usr/bin/expr $num_comp + 1`
                reseed_comps_flag=1
                stop_server_flag=1
                stop_agent_flag=1
                ;;
            f)
                sec_file_flag=1
                TMP_SEC_FILE="$OPTARG"
                if [ ! -f "$TMP_SEC_FILE" ]
                then
                    echo "file not found $TMP_SEC_FILE" 
                    exit 2
                fi
                ;;
            q)
                quite_flag=1
                ;;
            *)  num_comp=`/usr/bin/expr $num_comp + 1`
                print_script_usage
                ;;
         esac
      done
  
      if [ $num_comp -gt 1 ] ; then
          echolog ''
          echolog 'Invalid arguments.This combination of switches is not supported.'
          echolog 'Use $2 -h to print the usage of this script.' "$BASEDIR/sbin/es-config"
          exit 1
      fi
     
   fi        

   if [ $# -eq 0 ] ; then
      tmp_list=`/usr/bin/echo $L_SUNMC_PORTS | /usr/bin/sed 's/></,/g' | /usr/bin/sed 's/<//g' | /usr/bin/sed 's/>//' | /usr/bin/sed 's/,,/,/g' `
      [ ! -z "$tmp_list" ] && echolog 'The following ports are occupied by Sun Management Center:$2' "\n${tmp_list}."
      echolog ''

      printSnmpEncryptCfg

      echolog 'Use $2 -h to print the usage of this script.' "$BASEDIR/sbin/es-config"
      exit 0    
   fi

}


#
# Configure the database
#

reconfig_database() {
	
        /usr/bin/echo " \n "
        echolog " Reconfiguring the SGA parameters....... \n"

	pkginfo -qi SUNWessrv
        if [ $? -ne 0 ] ; then
            echolog "This option is for SunMC server only ... "
	    echolog "No changes made to configuration file ...Exiting...."
            return 1
        fi

	smc_get_physical_memory

        if [ $SMC_MEMSIZE -lt 512 ] ; then
            return $?
        fi
            ora_memory=`/usr/bin/expr $SMC_MEMSIZE / 2`
            
        if [ $ora_memory -gt 1024 ] ; then
            ora_memory=1024
        fi
            min_value=512
        if [ $sec_file_flag = "1" ]
            then
            db_config_from_file $ora_memory $min_value
            return $?
        else
            db_config_from_user $ora_memory $min_value
            return $?
        fi
        
   return $?

}


#
#get the value of parameters
#returns DB_BLOCK_BUFFERS SHARED_POOL_SIZE SHARED_POOL_RESERVED_SIZE
#

get_parameters() {


	DMC_VAR_PARAM=""
	config_file="$ESROOT/db/cfg/db-memconfig.cfg"
	rec_memory="$1"

	smc_get_config_sect "$config_file" "db_parm_var" DMC_VAR_PARAM;

	# Header to variable parameters
	for dmc_local_param in `/usr/bin/echo "$DMC_VAR_PARAM"|/usr/bin/sed -e 's/[ ]*//g`; do

	dmc_local_param_name=`/usr/bin/echo "$dmc_local_param"|/usr/bin/nawk -F= '{ print $1 }'`

	if [ "$dmc_local_param_name" = "db_block_buffers" ]; then
	DB_BLOCK_SIZE=0
	smc_get_config_section_key_value "$config_file" "db_parm_const" "db_block_size" DB_BLOCK_SIZE
	fi

	dmc_local_param_value=`/usr/bin/echo "$dmc_local_param"|/usr/bin/nawk -F= '{ print $2 }'`
	dmc_local_param_val=`/usr/bin/echo "$dmc_local_param_value"|/usr/bin/nawk -F: '{ print $1 }'`
	dmc_local_param_unit=`/usr/bin/echo "$dmc_local_param_value"|/usr/bin/nawk -F: '{ print $2 }'`


	if [ "$dmc_local_param_name" = "db_block_buffers" ]; then
	dmc_local_param_value=`/usr/bin/expr "$rec_memory" \* "$dmc_local_param_val" \* 1024 \* 1024 / 100 / $DB_BLOCK_SIZE`

	else
	dmc_local_param_value=`/usr/bin/expr "$rec_memory" \* "$dmc_local_param_val" / 100`
	fi

	if [ -n "$dmc_local_param_unit" ]; then
	  dmc_local_param_value="${dmc_local_param_value}${dmc_local_param_unit}"
	fi

	if [ "$dmc_local_param_name" = "db_block_buffers" ]; then
	  DB_BLOCK_BUFFERS=${dmc_local_param_value}
	elif [ "$dmc_local_param_name" = "shared_pool_size" ]; then
	  SHARED_POOL_SIZE=${dmc_local_param_value}
	elif [ "$dmc_local_param_name" = "shared_pool_reserved_size" ]; then
	  SHARED_POOL_RESERVED_SIZE=${dmc_local_param_value}
	fi
	done

}

#
# read from a file to config the database
#
db_config_from_file() {
	
        echo "Reading from the file $TMP_SEC_FILE "
	error_no=0
	ora_memory=`awk '/ora_memory/ {print $2}' $TMP_SEC_FILE`

	max_value=$1
	min_value=$2

	validate_user_input $ora_memory
	 if [ $? -eq 0 ] ; then
	  echolog "You have entered $ora_memory ...."
	  get_parameters $ora_memory
	  update_db_config_file $DB_BLOCK_BUFFERS $SHARED_POOL_SIZE $SHARED_POOL_RESERVED_SIZE

	else
	  echolog "Error in the format of your input file please check it properly and try again "
	  return 1
        fi
	
}

#
# This function is used to validate the user input for the given format
# it returns 0 for valid input 1 for invalid input and 2 for no input
#

validate_user_input() {
	
	 if [ -z "$1" ] ; then
	   echolog "No value is entered ......"
	   return 2
	 else
	     buffer=`echo $1 | sed '/[a-z]/d'`
	     if [ -z "$buffer" ] ; then
	        echolog "Error in the format of the entered value "
		echolog "please enter only the numbers Ex :- 512 \n"
		error_no=1
	     elif [ $ora_memory -lt $min_value} -o $ora_memory -gt $max_value ] ; then
	        echolog " Entered number is not in the range of recommended value "
		error_no=1
	     else
	        error_no=0
	     fi
	 fi

	if [ $error_no -eq 0 ] ; then
	 return 0
	else
	 return 1
        fi
}

#
#ask the user to enter the config parameters
#

db_config_from_user(){

	max_value=$1
	min_value=$2

	error_no=1

	while [ $error_no != 0 ]
        do
	get_input_from_user "Please enter the memory for SGA [min]$min_value-[max]$1 default is $1 :"
	ora_memory=$answer
	validate_user_input $ora_memory
	ret_value=$?
	 if [ $ret_value -eq 0 ] ; then
	 error_no=0
	 elif [ $ret_value -eq 2 ] ; then
	 ora_memory=$1
	 error_no=0
	 else
	 error_no=1
	 fi
	done

	if [ $error_no -eq 0 ] ; then
	echolog "Accepted value is $ora_memory .... "
	get_parameters $ora_memory
	update_db_config_file $DB_BLOCK_BUFFERS $SHARED_POOL_SIZE $SHARED_POOL_RESERVED_SIZE
	else
	echolog " parameters are not proper try again "
	 return 1
       fi

}

#
#accept parameters and update the database configuration file
#
update_db_config_file() {

	ORA_INITDIR=$BASEDIR/oracle/product/8.1.7/admin/SunMC/pfile
	ORA_INITFILE=$ORA_INITDIR/initSunMC.ora
	backup_file=$ORA_INITDIR/initSunMC.ora.backup

	tmp_file="/tmp/tmp_file.$$"
	tmp_file1="/tmp/tmp_file1.$$"

	/usr/bin/cat $ORA_INITFILE | sed 's/db_block_buffers[ ]*=[ ]*[0-9]*[a-z]*/db_block_buffers = '$1'/g' > $tmp_file
	/usr/bin/cat $tmp_file | sed 's/shared_pool_size[ ]*=[ ]*[0-9]*[MmKkGg]*/shared_pool_size = '$2'/g' > $tmp_file1
	/usr/bin/cat $tmp_file1 | sed 's/shared_pool_reserved_size[ ]*=[ ]*[0-9]*[MmKkGg]*/shared_pool_reserved_size = '$3'/g' > $tmp_file

       if [ $sec_file_flag != 1 ] ; then 
	proceed=0
	while [ $proceed = 0 ]
            do
	     get_input_from_user "Want to proceed....[ y/n,default y ] :"
             choice=$answer

	     if [ -z "$choice" ] ; then
		if [ ! -f "$backup_file" ] ; then
		/usr/bin/cp $ORA_INITFILE $backup_file
		fi
	        /usr/bin/cat $tmp_file > $ORA_INITFILE
		echolog "Successfull ........"
		proceed=1
             elif [ $choice = 'y' ] ; then
		if [ ! -f "$backup_file" ] ; then
		/usr/bin/cp $ORA_INITFILE $backup_file
		fi
		/usr/bin/cat $tmp_file > $ORA_INITFILE
		 echolog "Successfull ........"
		 proceed=1

	     elif [ $choice = 'n' ] ; then
		echolog "No changes made to configuration file ...Exiting...."
		echolog "Restart the Agent and Server ....."
		return 1
             else
	     echolog "Not a valid input Enter again....."
            fi
            done
	else
            if [ ! -f "$backup_file" ] ; then
		/usr/bin/cp $ORA_INITFILE $backup_file
            fi
	     /usr/bin/cat $tmp_file > $ORA_INITFILE
	     echolog "Successfull ........"
        fi
	/usr/bin/rm $tmp_file $tmp_file1
}

#
# print snmp encryption configuration
#
printSnmpEncryptCfg() {
    if [ $no_agent -ne 1 ]; then
        isEncryptInput
        if [ $? -eq 1 ]; then
	    echolog "Encrypted SNMP communication is supported."
        else
	    echolog "Encrypted SNMP communication is not supported."
	    return
        fi

        if [ $no_server -ne 1 ]; then
            isEncryptOutput
            if [ $? -eq 1 ]; then
		multiline_echolog "Sun Management Center server is configured to initiate encrypted SNMP\ncommunication."

	        isAutoNegotiate
	        if [ $? -eq 1 ]; then
		    echolog "The auto-negotiate feature is enabled."
	        else
		    echolog "The auto-negotiate feature is disabled."
	        fi
            else
		multiline_echolog "Sun Management Center server is not configured to initiate encrypted\nSNMP communication."
            fi
        fi

        echolog ''
    fi
}


#  $1 Can be one of the : topology, cfgserver, event, cstservice, trap, metadata, 
#                         agent, grouping, HTTP, HTTPS, platform  or a platfrom instances
#
configure_all_ports() {
    
    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
    [ $? -ne 0 -a -z "$AGENT_ESDIR" ] && AGENT_ESDIR="$VAROPTDIR"
    
    unset_env_variables
    change_esdir "$AGENT_ESDIR"
  
    configure_port "agent" 
    configure_port "platform" 
 
    # Get all platform instances
    #
    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`
       for each_instance in $list_of_instances
       do
           configure_port "$each_instance"
       done
    fi
    unset_env_variables
    change_esdir "$DEFAULT_ESDIR"

    configure_port "trap" 
    configure_port "event" 
 

    # Error handing for setup fail condiftions is already done.
    # 
    if [ $server_setup -eq 1 ]; then
       configure_port "topology" 
       configure_port "cfgserver" 
       configure_port "cstservice" 
       configure_port "metadata"
       configure_port "grouping" 
       configure_port "rmi" 
       configure_port "HTTP" 
       configure_port "HTTPS" 

    fi
    
}


#
# $1=component
# $2=port
# returns $port
#
#
#
#
ask_new_port () {
  
   echolog ''
   conflict_port_list=`/usr/bin/echo $L_SUNMC_PORTS | /usr/bin/sed s/"<$2>"//g 2> /dev/null`
  
   [ ! -z "$2" ] && echolog 'Sun Management center $2 component is presently using port:$3' "$1" "$2"
   echolog 'Press RETURN to continue with present configuration.'
   retcode=1

   READ_RESPONSE_ONCE=0
   while [ $retcode -ne 0 ]; do
      get_input_from_user 'Enter the port number you would like to use for $2 component [ 1100 to 65535 ]:' "$1"
      [ ! -z "$2" ] && [ -z "$answer" ] && answer="$2" && break
      
      /usr/bin/expr $answer + 1  1> /dev/null  2>&1 
      retcode=$?
      if [ $retcode -ne 0 ] ; then
         echolog 'Port $2 is not a valid port number. Try again.' "$answer"
         continue
      fi

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

      /usr/bin/echo "$conflict_port_list" | /usr/bin/grep -w $answer  > /dev/null
      if [ $? -ne 0 ]; then # Not used by other sunmc process
         /usr/bin/netstat -an | /usr/bin/grep "\*\.$answer " >/dev/null
         retcode=$?
         [ $retcode -gt 0 ] && break
         echolog 'The port you entered is busy. Try again.'
         retcode=1
      else
         retcode=1
         echolog 'This port is already used by other Sun Management Center component. Try again.'
      fi

   done
   
   port="$answer"

}

#
# Input - None
# finds list of all ports used by sunmc base product.
# Output - sets L_SUNMC_PORTS
#
find_all_sunmc_ports() {

   L_SUNMC_PORTS=""
   
   if [ $server_setup -eq 1 ] ; then
      tmp_sunmc_components="agent trap event topology cfgserver cstservice metadata platform grouping rmi HTTP HTTPS"
   else
      # Not applicable on console only installation. Check is done already.
      #
      tmp_sunmc_components="agent trap event platform"
   fi
	
   # Get all platform instances
   #
   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"
  
   for each_component in $tmp_sunmc_components
   do
       find_present_port $each_component
       port=`/usr/bin/echo "$port"  2> /dev/null`
       [ ! -z "$port" ] && L_SUNMC_PORTS="$L_SUNMC_PORTS<$port>"
   done

}

# Input $1 = sunmc component
#		- "agent topology cfgserver event cstservice trap metadata grouping HTTP HTTPS rmi"
#		- Or can be a paltform agent and platform instances
# Reurns : port
#
find_present_port() {

   port=""
   if [ "$1" = "grouping" ] ; then
      port=""
      if [ -x "$TOOLS_DIR/es-config-javaservice" ]; then
         port=`$TOOLS_DIR/es-config-javaservice | /usr/bin/grep ServiceRegistryPort | /usr/bin/cut -f2 -d "="  2> /dev/null`
         # No validation here. Will be done in ask_port_user later
      fi
   else
      if [ "$1" = "HTTP" -o "$1" = "HTTPS" ] ; then
         if [ -x "$TOOLS_DIR/es-config-webserver" ]; then
            port=`$TOOLS_DIR/es-config-webserver | /usr/bin/grep "$1:Port" | /usr/bin/cut -f3 -d ":"  2> /dev/null`
            # No validation here. Will be done in ask_new_port later
         fi
      else
          if [ "$1" = "rmi" ] ; then
             if [ -x "$TOOLS_DIR/es-config-server" ]; then
                 port=`$TOOLS_DIR/es-config-server | /usr/bin/grep rmiPort | /usr/bin/cut -f2 -d "="  2> /dev/null`
                 # No validation here. Will be done in ask_port_user later
             fi
          else
             port=`$XGET "$VARDIR/domain-config.x" "$1.snmpPort"  2> /dev/null`
          fi
      fi
   fi
   port=`/usr/bin/echo $port  2> /dev/null `  # remove spaces
}

# Input: $1=component
#	 $2=port
#
update_port() {

   [ -z "$2" ] && return 
   return_stat=1
  
   if [ "$1" = "grouping" ] ; then
      $TOOLS_DIR/es-config-javaservice -p $2 > /dev/null 2>&1
      return_stat=$?
   else
      if [ "$1" = "HTTP" -o "$1" = "HTTPS" ] ; then
         $TOOLS_DIR/es-config-webserver -p $1:$2 > /dev/null 2>&1
         return_stat=$?
      else
         if [ "$1" = "rmi" ] ; then
            $TOOLS_DIR/es-config-server -p $2 > /dev/null 2>&1
            return_stat=$?
         else
            $TOOLS_DIR/es-config-domain -p "${1}=$2" > /dev/null 2>&1
            return_stat=$?
            if [ $return_stat -eq 0 ] ; then

               # If not available, ask user.
               get_security_key 
               get_SNMPV1_community_string
               SECURITY_SEED="$security_seed"
               
               for each_instance in $list_of_instances
               do
                  if [ "$1" = "$each_instance" ] ; then
                      move_datfile "${VARDIR}/${each_instance}-usmussertbl-d.dat"
                      echolog 'Generating security keys for $2 component.' "$each_instance" 
                      if [ "$sec_file_flag" != "1" ]
                      then
                          $BASEDIR/base/sbin/base-usm-seed.sh -s "$security_seed" -v1 "$SNMPV1_STRING" -c $each_instance
                      else
                          $BASEDIR/base/sbin/base-usm-seed.sh -c $each_instance -f "$TMP_SEC_FILE"
                      fi
                      configure_community_string_file "${each_instance}"
                  fi
               done         

               if [ "$1" = "agent" -o "$1" = "platform" ]; then

                  echolog 'Generating security keys for $2 component.' "$1" 
                  generate_keys "$1" 0 "$security_seed" "$SNMPV1_STRING"
                  configure_community_string_file "$1"
               fi
            fi
         fi
      fi
   fi
   return $return_stat
}




# Edits entry from domain-config.x
# 
# $1 = config file parameter to check
#
configure_port () {
   
   [ -z "$L_SUNMC_PORTS" ] && find_all_sunmc_ports

   find_present_port "$1"
   
   [ -z "$port" ] && echolog 'Setup of $2 component not found.' "$1" && return 1

   oldport="$port"

   ask_new_port "$1" "$port"

   if [ $port != "$oldport" ] ; then
      update_port "$1" "$port"
      if [ $? -eq 0 ] ; then
          echolog 'Port updated for $2 component:$3' "$1" "$port"
          port_changed=1
      else
          echolog 'Error occured.'
          echolog 'Port not updated for $2 component.' "$1" 
      fi
   else
      echolog 'Port not updated for $2 component.' "$1" 
   fi

}

restore_default_ports () {
  
    echolog 'Restoring default port configuration of Sun Management Center components...'
  
    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
    [ $? -ne 0 -a -z "$AGENT_ESDIR" ] && AGENT_ESDIR="$VAROPTDIR"
    
    unset_env_variables
    change_esdir "$AGENT_ESDIR"
    update_port "agent" "161"
    update_port "platform" "166"
    unset_env_variables
    change_esdir "$DEFAULT_ESDIR"
  
    update_port "trap" "162"
    update_port "event" "163"
    update_port "topology" "164"
    update_port "cfgserver" "165"
    update_port "cstservice" "167"
    update_port "metadata" "168"
    update_port "grouping" "5600"
    update_port "rmi" "2099"
    update_port "HTTP" "8080"
    update_port "HTTPS" "8443"
   
    echolog 'You must ensure there are no port conflicts before starting Sun Management Center.'
    exit 0

}


# Sets globals required for script and textdomain
# Also checks proper status of sunmc setup.
#
setup_script_environment() {

   
   # Ensure that script is called by superuser
   #
   check_root
   
   umask 022

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

   create_temp_directory
   
   # 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.... 
   # 
   [ -z "$LOGFILE" ] && check_logfile "config"
   
   # Remove the port list file 
   #
   L_ALL_SUNMC_PORTS=""
   /usr/bin/rm -f ${TMP_DIR}/sunmc_ports.x

   set_xput
 
   # Find Sun Management Crenter installation and setup status
   #
   get_SunMC_setup_status
 
   if [ $no_server -eq 1 -a $no_agent -eq 1 ] ; then
      echolog 'Server or Agent layer is not installed.'
      exit 1
   fi

   sunmc_setup_error=0
   [ $no_server -eq 0 -a $server_setup -eq 0 ] && sunmc_setup_error=1
   [ $no_agent -eq 0 -a $agent_setup -eq 0 ] && sunmc_setup_error=1
   if [ $sunmc_setup_error -ne 0 ] ; then
      echolog 'Sun Management Center setup is not complete.'
      echolog 'Run $2 to setup Sun Management Center.' "$BASEDIR/sbin/es-setup -F"
      exit 1
   fi

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

   # This sets a list L_SUNMC_PORTS
   #
   find_all_sunmc_ports
   
}

# Any configuration change resulting in re-seeding requirement
# will set flag reseeding_required to 1
# 
update_configuration () {

   return_status=0
   if [ "$sec_file_flag" = "1" -a $config_db_flag != "1" ]
   then
       # get community string from file
        SNMPV1_STRING=`/usr/bin/grep ES_SNMPV1_STRING $TMP_SEC_FILE|/usr/bin/grep -v grep|/usr/bin/cut -d'=' -f2|/usr/bin/tr -d '\012'`
        if [ "$SNMPV1_STRING" = "" ]
        then
            echo "ES_SNMPV1_STRING not found"
            return 2
        fi
       # get security seed from file
       SECURITY_SEED=`/usr/bin/grep ES_SECURITY_SEED $TMP_SEC_FILE|/usr/bin/grep -v grep|/usr/bin/cut -d'=' -f2|/usr/bin/tr -d '\012'`
       if [ "$SECURITY_SEED" = "" ]
       then
           echo "ES_SECURITY_SEED not found"
           return 2
       fi
   fi
 
   if [ $configure_channels -eq 1 ] ; then
      $TOOLS_DIR/es-config-domain -c "${sunmc_component}"
      return_status=$?
   fi

   tmp_list=`/usr/bin/echo $L_SUNMC_PORTS | /usr/bin/sed 's/></,/g' | /usr/bin/sed 's/<//g' | /usr/bin/sed 's/>//' | /usr/bin/sed 's/,,/,/g' `
   [ ! -z "$tmp_list" ] && echolog 'The following ports are occupied by Sun Management Center:$2' "\n${tmp_list}."

   echolog ''
   printSnmpEncryptCfg

   if [ $configure_all_ports_flag -eq 1 ] ; then
      configure_all_ports  
      return_status=$?
   fi
     
   if [ $configure_single_port_flag -eq 1 ] ; then
      configure_port "$sunmc_port_component"
      return_status=$?
   fi
     
   if [ $restore_default_ports_flag -eq 1 ] ; then
      restore_default_ports
      return_status=$?
   fi
   
   if [ $configure_port_range_flag -eq 1 ] ; then
      configure_port_range
      return_status=$?
   fi

   if [ $configure_mcp_flag -eq 1 ] ; then
      configure_mcp
      return_status=$?
   fi

   if [ $configure_nat_flag -eq 1 ] ; then
      configure_addressing_mode
      return_status=$?
   fi

   if [ $reseed_comps_flag -eq 1 ] ; then
      reseed_comps
      return_status=$?
   fi

   if [ $config_db_flag -eq 1 ] ; then
	reconfig_database
	return_status=$?
   fi

   if [ "$configure_archivelog" -eq 1 ]; then
      if [ "$option" = "enable" ]; then
         ${TOOLS_DIR}/db-config-archive.sh -e 
         return_status=$?
      elif [ "$option" = "disable" ]; then
         ${TOOLS_DIR}/db-config-archive.sh -d 
         return_status=$?
      fi
   fi
 
   return "$return_status"
}

configure_port_range () {

   $TOOLS_DIR/es-config-domain -P "$MinPort:$MaxPort"  
   return $?   
    
}

configure_addressing_mode() {

    local_host=`/usr/bin/uname -n`

    LOGICAL_ADDRESS_MODE="name"
    echolog ''
    multiline_echolog 'Configure hostname for Sun Management Center.\nNote: the hostname entered below must be present in the hostmaps\nof all machines that must communicate with this host through NAT.'
        
    returncode=255
    while [ $returncode -ne 0 ]; do

        get_input_from_user "Enter hostname for this host [ $local_host ] : "
        if [ "$answer" = "" ] ; then
            answer="$local_host"
        fi

        isIpAddress "$answer"
        if [ $? -eq 1 ] ; then
            echolog 'You must enter a valid hostname, IP addresses are invalid when NAT is enabled.'
        else
            validate_host "$answer"
            if [ $? -ne 0 ] ; then
                echolog 'Host $2 not pingable. Try again.' "$answer"
            else
                returncode=0
            fi
        fi
        echolog ''
    done
     
    agent_host="$answer"
    server_host="$answer" 
    
    if [ $no_server -eq 1 ] ; then
  
        echolog ''
        echolog 'Sun Management Center server is not installed locally.'
        echolog 'You must configure hostname for Sun Management Center server.'
        multiline_echolog 'Note: the hostname entered below must be present in the hostmaps\nof all machines that must communicate with Management Center server host through NAT.'
        set_xput
        server_host=`$XGET ${VARDIR}/domain-config.x trap.trapServer`

        retcode=1
        while [ $retcode -ne 0 ]; do
            get_input_from_user 'Enter the Sun Management Center Server Hostname [ $server_host ] : '
            [ ! -z "$answer" ] && server_host="$answer"

            retcode=1
            isIpAddress "$server_host"
            if [ $? -eq 1 ] ; then
                echolog "You must enter a valid hostname, IP addresses are invalid when NAT is enabled."
            else
                validate_host "$server_host"
                if [ $? -ne 0 ] ; then
                    echolog 'Host $2 not pingable. Try again.' "$server_host"
                else
                    retcode=0
                fi
            fi

            if [ "$retcode" = "0" ] ; then
                if [ "$server_host" = "`/usr/bin/hostname`" ] ; then
                    echolog 'Sun Management Center server is not installed locally.'
                    echolog 'Enter a valid Sun Management Center server name.'
                    retcode=1
                fi
            fi
       done
       echolog ''
    fi

    AGENT_ESDIR=`$API_QUERY_REGISTRY "$REGISTRY" "category=Installation" "layer=LAYER.AGENT" "agent-cfg-dir" 2> /dev/null `
    [ $? -ne 0 -a -z "$AGENT_ESDIR" ] && AGENT_ESDIR="$VAROPTDIR"
    
    unset_env_variables
    change_esdir "$AGENT_ESDIR"
  
    configure_nat "agent" "$agent_host"
    configure_nat "platform" "$agent_host"
 
    # Get all platform instances
    #
    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`
       for each_instance in $list_of_instances
       do
           configure_nat "$each_instance" "$agent_host"
       done
    fi
    unset_env_variables
    change_esdir "$DEFAULT_ESDIR"

    configure_nat "trap" "$server_host" 
    configure_nat "event" "$server_host"
 
    # Error handing for setup fail condiftions is already done.
    # 
    if [ $server_setup -eq 1 ]; then
       configure_nat "topology" "$server_host"
       configure_nat "cfgserver" "$server_host"
       configure_nat "cstservice" "$server_host"
       configure_nat "metadata" "$server_host"

       # Take care of index.html.
       #
       WEBSERVER_CONFIG_FILE="${BASEDIR}/web/conf/server.xml"
       MLTIP_FILE="$ESDIR/cfg/multiip.dat"
       if [ -r "$WEBSERVER_CONFIG_FILE" ]; then
          if [ -r "$MLTIP_FILE" ]; then
             iplist=`$XGET $MLTIP_FILE 0 2> /dev/null `
             secondary_host=`/usr/bin/echo $iplist| /usr/bin/cut -f2 -d":" 2> /dev/null `
             secondary_host=`/usr/bin/echo $secondary_host 2> /dev/null`
             if [ ! -z "$secondary_host" ] ; then
                multiline_echolog 'Sun Management Center server is configured to use more than one network interface.\nHowever, only Primary network interface will be enabled for Sun Management Center\nweb console when NAT is enabled.'
             fi
          fi

          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 `
          http_free_port=`/usr/bin/echo $port | /usr/bin/cut -f2 -d' '  2> /dev/null `
          /usr/bin/cat ${BASEDIR}/web/console/index.tmp | /usr/bin/sed "s/Port/$http_free_port/" > ${VAROPTDIR}/web/index.tmp
          /usr/bin/sed "s/hostname/$server_host/" ${VAROPTDIR}/web/index.tmp |/usr/bin/sed "s/ip_address/$server_host/" > ${VAROPTDIR}/web/index.html
          /usr/bin/ln -s ${VAROPTDIR}/web/index.html ${BASEDIR}/web/console/index.html >/dev/null 2>&1
          /usr/bin/rm ${VAROPTDIR}/web/index.tmp
       else
          echolog 'Error in web server setup.'
          echolog 'Web Server may not function properly.'
       fi
    fi

    echolog 'NAT support is enabled for this host.'

}

configure_nat() {
   $XPUT $VARDIR/domain-config.x "$1.logicalAddressMode" "$LOGICAL_ADDRESS_MODE"
   $XPUT "${VARDIR}/domain-config.x" $1.$1Server "$2"
}


configure_mcp () {
    CONFIG_FILE="$VAROPTDIR/cfg/es-mcp-users"

    #
    # Check for the presence of SUNWesmcp
    #
    /usr/bin/pkginfo -qi SUNWesmcp
    if [ $? -ne 0 ] ; then
	echolog "Module Configuration Propagation is not installed."
	return 1
    fi

    echolog ""
    echolog "Welcome to Module Configuration Propagation Setup"
    echolog ""
    multiline_echolog 'This setup allows you to add a comma-delimited list of\nusernames to the es-mcp-users configuration file that is\nlocated in $2.' "${VAROPTDIR}/cfg"
    echolog ""
    multiline_echolog "This list will be used to check whether a user is authorized\nto propagate action scripts to this machine."
    echolog ""
    echolog "This file is not required for a server layer installation."
    multiline_echolog "If the file is empty for a server layer installation,\nall users who belong to the esadm group (c.f. /etc/group)\nwill be authorized."
    echolog ""
    echolog "You may edit the file manually after the setup."
    echolog ""

    get_input_from_user "Add a comma-delimited list of usernames:"
    if [ -f $CONFIG_FILE ]; then
	/usr/bin/rm -f $CONFIG_FILE
    fi
    if [ "$answer" != "" ]; then
	for USER in `echo $answer | awk 'BEGIN { FS="," } { for (i = 1; i <= NF; i++) print $i }'`
	do
	    echo $USER >> $CONFIG_FILE
	done
	chmod 644 $CONFIG_FILE
    fi
    return $?
}

#
#Check if system supports auto-negotiate
#
isAutoNegotiate() {
    auto=`$XGET $VAROPTDIR/cfg/domain-config.x security.autoNegotiate`
    return $auto
}

#
# Ask if need auto-negotiate
#
askAutoNegotiate() {
    echolog ''
    multiline_echolog 'The auto-negotiate feature enables the Sun Management Center server to\nautomatically use encrypted communication with agents that support SNMP\nencryption, and to use authenticated communication with agents that do\nnot support SNMP encryption.'

    echolog ''

    fetch_response_yes_no "Do you want to enable the auto-negotiate feature "
    [ $? -gt 0 ] && exit $?

    echolog ''
    return $answer
}

#
reseed_comps () {

    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`

    COMPS="agent platform $list_of_instances"
    SERVERCOMPS="metadata cfgserver event cstservice topology trap"

    [ "$no_server" -ne "1" ] && COMPS="$COMPS $SERVERCOMPS"
   
    if [ "$sec_file_flag" != "1" ]
    then
        get_security_key 
        get_SNMPV1_community_string
    fi
   
    # reseed agent and server
    #
    generate_keys agent 0 "$security_seed" "$SNMPV1_STRING" "$TMP_SEC_FILE"

    if [ "$no_server" -eq "0" ]; then
        generate_keys server 0 "$security_seed" "$SNMPV1_STRING" "$TMP_SEC_FILE"
    fi

    # reseed platform instances
    #
    for comp in $list_of_instances
    do
       move_datfile "${VARDIR}/${comp}-usmussertbl-d.dat"
    done

    if [ "$list_of_instances" -ne "" ]; then
        if [ "$sec_file_flag" != "1" ]; then
            $BASEDIR/base/sbin/base-usm-seed.sh -s "$security_seed" -v1 "$SNMPV1_STRING" -c $list_of_instances
	else
            $BASEDIR/base/sbin/base-usm-seed.sh -c $list_of_instances -f "$TMP_SEC_FILE"
	fi
    fi

    # configure community string
    #
    for comp in $COMPS
    do
       configure_community_string_file "${comp}"
    done

    #
    # Only server can use snmp privacy.
    #
    [ "$no_server" -eq "1" ] && return 0

    isEncryptInput
    [ $? -ne 1 ] && return 0

    #
    # default setting is no snmp privacy
    #
    DOMAIN_CONFIG_FILE="${VAROPTDIR}/cfg/domain-config.x"
    SECURITY_SERVER=AuthenticationNoPrivacy
    SECURITY_AGENT=auth
    NEGOTIATE_SERVER=false
    NEGOTIATE_AGENT=0

    multiline_echolog 'Sun Management Center server layer can initiate encrypted SNMP communication\nwith agents that support encryption.'
    echolog ''

    fetch_response_yes_no "Do you want to configure this server to initiate encrypted SNMP communication "
    [ $? -gt 0 ] && return $?

    echolog ''

    if [ $answer -eq 1 ]; then
        SECURITY_SERVER=AuthenticationPrivacy
        SECURITY_AGENT=priv

	askAutoNegotiate
	if [ $? -eq 1 ]; then
	    NEGOTIATE_SERVER=true
	    NEGOTIATE_AGENT=1
	    multiline_echolog "The Sun Management Center server is configured to initiate encrypted SNMP\ncommunication with auto-negotiate enabled."
	else
	    multiline_echolog "The Sun Management Center server is configured to initiate encrypted SNMP\ncommunication with auto-negotiate disabled."
	fi

    else
	multiline_echolog "Sun Management Center server is not configured to initiate encrypted\nSNMP communication."
    fi

    echolog ''

    # update the domain-config property
    #
    $XPUT $DOMAIN_CONFIG_FILE "security.securityLevel" ${SECURITY_AGENT}
    $XPUT $DOMAIN_CONFIG_FILE "security.autoNegotiate" ${NEGOTIATE_AGENT}

    # update the javaserver properties
    #
    JAVASERVER_CONFIG_FILE="${VAROPTDIR}/cfg/javaserver.properties"
    /usr/bin/mv -f "$JAVASERVER_CONFIG_FILE" "${JAVASERVER_CONFIG_FILE}.old"
    /usr/bin/sed "s/^ *snmp_SecurityLevel = .*$/snmp_SecurityLevel = $SECURITY_SERVER/; s/^ *snmppublic_SecurityLevel = .*$/snmppublic_SecurityLevel = $SECURITY_SERVER/; s/^ *AutoNegotiate = .*$/AutoNegotiate = $NEGOTIATE_SERVER/" "${JAVASERVER_CONFIG_FILE}.old" > "$JAVASERVER_CONFIG_FILE"

    # read/write only by the owner
    #
    /usr/bin/chmod 600 $JAVASERVER_CONFIG_FILE

    return $?
}


stop_selected_components() {
   
   [ "$stop_server_flag" = "1" ] && $BASEDIR/sbin/es-stop -S
   [ "$stop_agent_flag" = "1" ] && $BASEDIR/sbin/es-stop -alY
}


start_selected_components() {
   echo ""
   echolog "Starting components..."
   echo ""
   [ "$stop_server_flag" = "1" ] && $BASEDIR/sbin/es-start -S
   [ "$stop_agent_flag" = "1" ] && $BASEDIR/sbin/es-start -alY
}

# << END functions used by this script <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #

#########################################################################
# Main 
#########################################################################

   setup_script_environment

   process_script_options "$@"

   stop_selected_components

   update_configuration
   [ $? -eq 0 ] && [ $quite_flag -eq 0 ]  && [ "$configure_archivelog" -eq 0 ] && start_selected_components
   
   exit 0

#########################################################################



