################################################################################
# Keys to performance tuning parameter documentation:    
#           IS      - Identity Server
#           DS      - Directory Server
#           WS      - Web Server
#           AS      - Application Server
#           amtune  - Identity Server tuning scripts located in amtune directory
#           #x      - Number of x (eg. #Sessions - Number of Sessions) 
#           KB      - Kilo Bytes
#           MB      - Mega Bytes
#           GB      - Giga Bytes
#           MTS     - Minutes
#           SM      - IS Service Management Module
#           NYI     - Not yet incorporated
#
# You will need to modify/verify the parameters mentioned below for perftune/* 
# scripts to work as designed.
#
# All parameters prefixed by AMTUNE are used by the amtune scripts
# 
# The following entries can be modified to suit your deployment.
# Once you have edited this file, you may run any of the amtune scripts.
# Usage:
#       <amtune-script> <admin_password> <dirmanager_password>
#
# Note that amtune currently is non-interactive.
#
# Also, there is a list of "DO NOT MODIFY" parameters towards the end of this file
# that the amtune scripts rely on. This section is maintained by IS engineers
# and modifications to these parameters are unwarranted and will not be supported.
#
################################################################################
############### Start : Performance Related User Inputs #######################
################################################################################
#-------------------------------------------------------------------------------
# Parameter     :   AMTUNE_MODE
# Values        :   REVIEW, CHANGE
# Default       :   REVIEW
#
# Description   :   Based on this setting, the amtune scripts will behave differently
#
#                   1. REVIEW - Suggest Tuning mode (default)
#                       - In this mode, amtune will suggest tuning recommendations but will not 
#                       make any changes to the deployment
#
#                       This mode will honor AMTUNE_DEBUG_FILE_PREFIX parameter.
#                       List of tuning recommendations along with the current values will be 
#                       noted in the debug file and console.
#
#                   2. CHANGE - Change Mode 
#                       - In this mode, amtune scripts will perform
#                       all changes deemed necessary. 
#                       (Except for Directory Tuning. Read Note below)
#
#                       This mode will honor AMTUNE_DEBUG_FILE_PREFIX parameter.
#                       List of changes along with the original values will be noted 
#                       in the debug file and console.
#
# Note          :   1. On CHANGE mode
#                   Please use extreme caution while using CHANGE mode.
#                   In CHANGE mode, amtune might need to restart the Web Container, Identity
#                   and might recommend a system restart.
#   
#                   2. On Directory Server tuning   
#                   Tuning Directory Server requires extra levels of confirmation.
#                   Assumption is that Identity will use an existing Directory Server in
#                   non-exclusive mode (other applications might use Directory Server)
#                   
#                   Irrespective of where the Directory Server is installed (local or remote),
#                   Directory Server will not be tuned automatically. Only a tar file
#                   containing the Directory Server tuner scripts will be created. You will need
#                   to untar this in a location such as /tmp on the Directory Server machine
#                   and execute the amtune-ds script.
#                   
#                   3. On selectively tuning different components
#                   Different components (such as OS, Web Container, Identity, Directory)
#                   can be selectively based on AMTUNE_TUNE_* parameters. (Described in
#                   detail next in the next comment block)
#-------------------------------------------------------------------------------
AMTUNE_MODE="REVIEW"

#-------------------------------------------------------------------------------
# Parameters    :   AMTUNE_TUNE_*
# Value         :   true or false
# Default       :   true
#
# Description   :   You can choose specific components to be tuned by the tuner scripts
#                       Components to tune:
#                       a) AMTUNE_TUNE_OS               - Operating System - Kernel, TCP settings
#                       b) AMTUNE_TUNE_DS               - Directory Server
#                       c) AMTUNE_TUNE_WEB_CONTAINER    - Web Container - Application Server or Web Server
#                       d) AMTUNE_TUNE_IDENTITY         - Identity Server
#                   These settings work in conjunction with AMTUNE_MODE parameter setting.
#                   You could review or change recommended tunings of any set of components.
#
# Note          :   Read note 2 on AMTUNE_MODE
#-------------------------------------------------------------------------------
AMTUNE_TUNE_OS=true
AMTUNE_TUNE_DS=true
AMTUNE_TUNE_WEB_CONTAINER=true
AMTUNE_TUNE_IDENTITY=true

#-------------------------------------------------------------------------------
# Installation Environment
#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------
# Parameter     :   HOSTNAME
# Value         :   Host name 
# Default       :   `/bin/hostname`
#
# Description   :   If the hostname for your environment cannot be obtained through hostname comamnd,
#                   please comment the following line and add a line setting the right hostname. 
#                   eg. HOSTNAME=xyz
#-------------------------------------------------------------------------------
HOSTNAME=`/bin/hostname | /bin/cut -f1 -d"."`

#-------------------------------------------------------------------------------
# Parameter     :   DOMAINNAME
# Value         :   Domain Name
# Default       :   `/bin/domainname`
#
# Description   :   If domainname for your environment cannot be obtained through domainname command,
#                   please comment the following line and add a line setting the right domainname. 
#                   eg. DOMAINNAME=yyy.com
#-------------------------------------------------------------------------------
DOMAINNAME=`/bin/domainname`

if [ "$HOSTNAME" != "" ] && [ "$DOMAINNAME" != "" ]; then
    HOSTNAME=${HOSTNAME}.${DOMAINNAME}
fi

#-------------------------------------------------------------------------------
# Parameter     :   IS_CONFIG_DIR
# Value         :   Identity configuration directory
# Default       :   /etc/opt/SUNWam/config
#
# Description   :   Typical value is the default value. There should be no 
#                   reason to change this value.
#-------------------------------------------------------------------------------
IS_CONFIG_DIR=/etc/opt/SUNWam/config

#-------------------------------------------------------------------------------
# Parameter     :   WEB_CONTAINER
# Values        :   WS61 or AS7
#
# Description   :   Name of the Web Container that IS is deployed on.
#                   Accepted values for WEB_CONTAINER
#                   WebServer6.1=WS61, AppServer=AS7
#
#                   If you specify any other value, you will receive a
#                   validation error
#-------------------------------------------------------------------------------
WEB_CONTAINER=WS61

#-------------------------------------------------------------------------------
# Parameter     :   CONTAINER_BASE_DIR
# Value         :   Identity Web Container's Install Directory
# Default       :   /opt/SUNWwbsvr                              - for Web Server 6.1 or later
#                   /var/opt/SUNWappserver7/domains/domain1     - for Application Server 7.0 or later
#
# Description   :   Typical value is the default value specified for each container.
#                   If you install the web container in a non-default location, 
#                   you will need to change this value
#-------------------------------------------------------------------------------
if [ "$WEB_CONTAINER" = "" ] || [ "$WEB_CONTAINER" = "WS61" ]; then
    CONTAINER_BASE_DIR=/opt/SUNWwbsvr
else
    CONTAINER_BASE_DIR=/var/opt/SUNWappserver7/domains/domain1
fi

#-------------------------------------------------------------------------------
# Parameter     :   WEB_CONTAINER_INSTANCE_NAME
# Values        :   <web container instance name>
# Default       :   ${HOSTNAME}
#
# Description   :   Typically, this value is the hostname where IS is deployed.
#                   When you have multiple instances for the web container,
#                   this value might be different from the hostname.
#                   Please customize this accordingly
#                   
#-------------------------------------------------------------------------------
if [ "$WEB_CONTAINER" = "" ] || [ "$WEB_CONTAINER" = "WS61" ]; then
    WEB_CONTAINER_INSTANCE_NAME=${HOSTNAME}
else
    WEB_CONTAINER_INSTANCE_NAME=server1
fi

#-------------------------------------------------------------------------------
# Parameter     :   IS_INSTANCE_NAME
# Value         :   Identity Server Instance Name
# Default       :   <empty>
#                   
#
# Description   :   This value is used in determining the property
#                   filenames for the IS install.
#                   Multiple instances of IS could be deployed in the same machine.
#                   Assumption is that there will be one set of property files
#                   per IS instance and the instance name will be appended to the 
#                   file names.
#                   If there is only one instance of IS in a machine, then 
#                   the instance name will not be appended to the file names
#   
#                   e.g. If your IS is installed on a machine named server.sun.com,
#                   typically, your first instance of the web server will be 
#                   https-server.sun.com.
#                   The property files for the first IS instance will not have 
#                   the instance name appended. (AMConfig.properties)
#                   In case of multiple instances, you will have different names.
#                   lets take an example of 3 instances. Instances could be 
#                   server.sun.com-instance1, server.sun.com-instance2, 
#                   server.sun.com-instance3. 
#                   If 3 instances of IS are deployed, one per container instance,
#                   then the property files will look something like the following:
#                   AMConfig-instance1.properties
#                   AMConfig-instance2.properties
#                   AMConfig-instance3.properties
#               
#                   You can specify IS_INSTANCE_NAME=instance1. 
#                   AMTUNE will resolve the property file names in the following order:
#                   in the following order (eg. AMConfig.properties) :
#                   1. AMConfig-<IS_INSTANCE_NAME>
#                   2. AMConfig-<WEB_CONTAINER_INSTANCE_NAME>
#                   3. AMConfig.properties
#                  
#                   The tool will use the first available property file in the list and use 
#                   it.
#                   
#                   Another important note here is that the tool "amadmin" should
#                   point to the correct server name as well (java option -Dserver.name=<IS_INSTANCE_NAME>)
#                   
# Significance  :   AMTune will automatically try to associate your instance names with 
#                   IS Property files using this parameter.
#                   Currently, only 2 files are based on this Instance Name
#                       a. AMConfig.properties file
#                       b. serverconfig.xml
#-------------------------------------------------------------------------------
IS_INSTANCE_NAME=

#-------------------------------------------------------------------------------
# Parameter     :   CONTAINER_INSTANCE_DIR
# Value         :   Identity Web Container instance directory
# Default       :   $CONTAINER_BASE_DIR/https-${WEB_CONTAINER_INSTANCE_NAME}    - for Web Server 6.1 or later
#                   $CONTAINER_BASE_DIR/https-${WEB_CONTAINER_INSTANCE_NAME}    - for Application Server 7.0 or later
#
# Description   :   Typical value is the default value. If you install Identity in a
#                   non-default location, you will need to change this value
#-------------------------------------------------------------------------------
if [ "$WEB_CONTAINER" = "" ] || [ "$WEB_CONTAINER" = "WS61" ]; then
    CONTAINER_INSTANCE_DIR=$CONTAINER_BASE_DIR/https-${WEB_CONTAINER_INSTANCE_NAME}
else
    CONTAINER_INSTANCE_DIR=$CONTAINER_BASE_DIR/${WEB_CONTAINER_INSTANCE_NAME}
fi

#-------------------------------------------------------------------------------
# Directory stuff
#-------------------------------------------------------------------------------
DIRMGR_UID="cn=Directory Manager"
RAM_DISK=/tmp

#-------------------------------------------------------------------------------
# Parameter     :   DEFAULT_ORG_PEOPLE_CONTAINER
# Value         :   Default Organization's People container name
# Description   :   This value is used to tune the LDAP Auth Module's
#                   search base. This can be a very useful tuning 
#                   parameter when there are no sub-orgs in the default
#                   organization
#                   If this value is set to empty, the tuning will be skipped
# Note          :   Along with appending the people container to the search base,
#                   the search scope will be modified to "OBJECT" level. Default
#                   search scope is "SUBTREE"
#-------------------------------------------------------------------------------
DEFAULT_ORG_PEOPLE_CONTAINER="ou=People"

#-------------------------------------------------------------------------------
# Parameter     :   AMTUNE_DEBUG_FILE_PREFIX
# Values        :   <log file name prefix>
# Default       :   amtune
# Note          :   Here, you specify just the prefix name for the file.
#                   The file will be automatically created in the debug directory for this deployment
#                   based on the AMConfig.property "com.iplanet.services.debug.directory"
#
# Description   :   If this value is set to a non-empty value, then
#                   all the operations performed by amtune scripts will be logged.
#                   AMConfig.property's "com.iplanet.services.debug.directory=" setting
#                   dictates where the file will be created.
#
#                   In future, amtune might be intelligent enough to also 
#                   provide different levels of information based on "com.iplanet.services.debug.level"
#                   setting.
#                   
# Significance  :   If this value is not specified, then no debugging information
#                   will be recorded. Essentially, all output will go to /dev/null
#-------------------------------------------------------------------------------
AMTUNE_DEBUG_FILE_PREFIX=amtune

#-------------------------------------------------------------------------------
# Parameter     :   AMTUNE_PCT_MEMORY_TO_USE
# Values        :   0-100
# Default       :   75
# Description   :   Percentage value; Dictates how much of available memory
#                   will be used by IS
# Note          :   Currently, IS can use a maximum of 4GB. This is the 
#                   per-process address space limit for 32-bit apps.
#
#                   IS currently requires a minimum of 256MB RAM
#
#                   When you set AMTUNE_PCT_MEMORY_TO_USE to 100, the maximum 
#                   space allocated for IS would be the minimum between 4GB
#                   and 100% of available RAM
#
#                   When you set AMTUNE_PCT_MEMORY_TO_USE to 0, IS will be 
#                   configured to use 256MB RAM 
#                   
# Significance  :   This value is the driving force in tuning IS.
#                   The following values are derived from this setting:
#                   1. JVM memory usage - Heap Sizes, NewSizes, PermSizes
#                   2. ThreadPool sizes - WS RqThrottle, 
#                           Authentication LDAP Connection Pool,
#                           SM LDAP Connection Pool,
#                           Notification ThreadPools
#                           
#                   3. IS Caches - SDK Caches, Session Caches (NYI: Policy Caches)
#                   4. Max Sizes - Max. #Sessions, Max #CacheEntries
#                   
#-------------------------------------------------------------------------------
AMTUNE_PCT_MEMORY_TO_USE=75

#-------------------------------------------------------------------------------
# Parameter     :   AMTUNE_PER_THREAD_STACK_SIZE_IN_KB
# Value         :   <value in KB>
# Default       :   128 (KB)
#               
#
# Description   :   This value is the available stack space per thread in Java(/Web Container).
#                   Per thread stack size is used to tune various thread related
#                   parameters in IS and the Web Container.
#                   
#                   128 KB is a reasonable value for this, and should not be 
#                   changed unless otherwise absolutely necessary
#-------------------------------------------------------------------------------
AMTUNE_PER_THREAD_STACK_SIZE_IN_KB=128

#-------------------------------------------------------------------------------
# Parameters    :   AMTUNE_SESSION_MAX_SESSION_TIME_IN_MTS
#                   AMTUNE_SESSION_MAX_IDLE_TIME_IN_MTS
#                   AMTUNE_SESSION_MAX_CACHING_TIME_IN_MTS
# Values        :   Max Session Time, Max Idle Time, Max Session Caching Time in minutes
# Default       :   AMTune will not tune these parameters by default. See Note below.
#                   Max Session Time default    - 60 minutes
#                   Session Max Idle Time       - 10 minutes
#                   Session Max Caching Time    - 02 mintues
#
# Description   :   The following three values will change the global session timeout 
#                   values. If Session Service is registered and customized at any other
#                   level, the tuning will not apply to them
#
# Significance  :   Setting this value to very high or very low values (minutes) will affect the
#                   number of users an IS deployment can support. Hence, these parameters
#                   could be optionally tuned using this tool
#
# Note          :   You will have to explicitly enable session timeout tuning by setting
#                   AMTUNE_DONT_TOUCH_SESSION_PARAMETERS=false.
#                   Dont assume that that the defaults provided are correct. 
#
#   USE THIS TUNING OPTION WITH CARE!!!
#-------------------------------------------------------------------------------
AMTUNE_DONT_TOUCH_SESSION_PARAMETERS=true
AMTUNE_SESSION_MAX_SESSION_TIME_IN_MTS=60
AMTUNE_SESSION_MAX_IDLE_TIME_IN_MTS=10
AMTUNE_SESSION_MAX_CACHING_TIME_IN_MTS=2

################################################################################
############### End: Performance Related User Inputs ###########################
################################################################################

################################################################################
############### Start: amtune Internals ########################################
############### DO NOT MODIFY BELOW THIS LINE ##################################
################################################################################
#===============================================================================
# amtune Constants
#===============================================================================
#Min and Max per IS installation RAM
AMTUNE_MIN_MEMORY_TO_USE_IN_MB=512
AMTUNE_MAX_MEMORY_TO_USE_IN_MB_SOLARIS=3584
AMTUNE_MAX_MEMORY_TO_USE_IN_MB_LINUX=2048
AMTUNE_MAX_MEMORY_TO_USE_IN_MB_DEFAULT=2048
AMTUNE_MAX_MEMORY_TO_USE_IN_MB_X86=$AMTUNE_MAX_MEMORY_TO_USE_IN_MB_DEFAULT

AMTUNE_MIN_PERM_SIZE_WS61=192
AMTUNE_MIN_PERM_SIZE_AS7=225

#Sizes are estimates based on actual usage obtained thru JProbe
AMTUNE_AVG_PER_ENTRY_CACHE_SIZE_IN_KB=8
AMTUNE_AVG_PER_SESSION_SIZE_IN_KB=4

#Per thread stack size is a JDK recommended value
AMTUNE_DEF_PER_THREAD_STACK_SIZE_IN_KB=128

#WS uses about 1/8 of the IS process memory. Hence this setting
AMTUNE_MEM_AVAIL_FOR_JAVA=7/8

#Out the memory available for Java part of the IS process memory, 
#the following is the breakdown of memory needs
AMTUNE_MEM_MAX_NEW_SIZE=1/8
AMTUNE_MEM_MAX_PERM_SIZE=1/12
AMTUNE_MEM_THREADS_SIZE="(1/16)*($AMTUNE_DEF_PER_THREAD_STACK_SIZE_IN_KB/$AMTUNE_PER_THREAD_STACK_SIZE_IN_KB)"
AMTUNE_MEM_OPERATIONAL=19/48
AMTUNE_MEM_CACHES_SIZE=1/3

#Out of the memory available for IS Caches, 
#the breakdown b/w SDK and Session Cache size is as follows:
#NOTE   :   Its not clear how much memory Policy, Liberty, SAML Caches use. 
#           These fall into the OPERATIONAL memory category. 
#           Once we have an estimate on them, will adjust these values appropriately. 
#           OPERATIONAL memory is large enough to handle these unknown quantities
#
AMTUNE_MEM_SDK_CACHE_SIZE=2/3
AMTUNE_MEM_SESSION_CACHE_SIZE=1/3

#Notification queue size is estimated to be 10% of concurrent sessions
#Basically, IS can operate properly as long as 10% or less sessions expire under a short period of time
#Current estimation of "short period of time" is 5-10 minutes.
AMTUNE_NOTIFICATION_QUEUE_SIZE=1/1000

AMTUNE_MAX_NUM_THREADS="$AMTUNE_MEM_THREADS_SIZE*(1024/$AMTUNE_PER_THREAD_STACK_SIZE_IN_KB)"

#WS internal threads used. This is not really factored into any calculation.
#But, nevertheless, its useful to know how much we estimated. Typical value for this
#is about 50. But, we leave one more fold contingent threads
AMTUNE_NUM_WS_INTERNAL_THREADS=100

#Established Thread Counts 
AMTUNE_NUM_JAVA_INTERNAL_THREADS=8
AMTUNE_NUM_JAVA_APPS_DEPLOYED=6
AMTUNE_NUM_IS_INTERNAL_THREADS=3

#After all the known threads are taken into account, we still plan for about a 3rd more
#threads in the system.
#The tuner program will figure out how much memory can be used up by threads and reserves 
# 1/3 of them for unplanned threads
AMTUNE_THREADS_UNPLANNED=1/3

#Known threads breakdown
AMTUNE_WS_RQTHROTTLE_THREADS=5/12
AMTUNE_IS_OPERATIONAL_THREADS=5/12
AMTUNE_IS_AUTH_LDAP_THREADS=1/12
AMTUNE_IS_SM_LDAP_THREADS=1/24
AMTUNE_IS_NOTIFICATION_THREADS=1/48

#Defines how many notifications can be in the pending queue per notification thread
AMTUNE_IS_NOTIFICATION_QUEUE_SIZE_PER_THREAD=100

#Some known WS and IS Defaults
AMTUNE_NUM_WS_RQTHROTTLE_MIN=10
AMTUNE_NUM_WS_THREAD_INCREMENT=10
AMTUNE_NUM_IS_MIN_AUTH_LDAP_THREADS=10
AMTUNE_WS_ACCEPTOR_PER_CPU_MULTIPLIER=2
AMTUNE_NUM_ACCEPTOR_THREADS=2

#Just plain constants
AMTUNE_NUM_FILE_DESCRIPTORS=65536
AMTUNE_NUM_TCP_CONN_SIZE=8192

#AMTune Error Status Codes
AMTUNE_INVALID_CMDLINE_PARAMETER=100
AMTUNE_INVALID_ENVIRON_SETTING=200

#############################################################################
# amtune functions
#############################################################################
getUsage() {
    $ECHO `$gettext "Usage:"`
    $ECHO `$gettext "You can use amtune scripts in two ways:"`
    $ECHO `$gettext "1. Use the wrapper script - amtune"`
    $ECHO `$gettext "2. Use individual scripts  - amtune-<component name>"` 
    $ECHO
    $ECHO `$gettext "Mandatory Parameter for the scripts:"`
    $ECHO `$gettext "1. Identity Server Admin Client Utility Password"`
    $ECHO `$gettext "2. Directory Manager ($DIRMGR_UID) Password"`
    $ECHO
    $ECHO `$gettext "Sample Command Line:"`
    $ECHO `$gettext "<amtune-script> <admin_password> <dirmanager_password>"`
    $ECHO 
    $ECHO `$gettext "Please make sure to customize amtune-env to suit your deployment."`
}
#############################################################################
# Start of main program
#############################################################################
ADMIN_PASSWORD=$1
DIRMGR_PASSWORD=$2

SCRIPT_BASENAME=`/bin/basename $0`
SCRIPT_LOCATION=`/usr/bin/dirname $0`

if [ ! -d $SCRIPT_LOCATION/../.. ]; then
    /bin/echo `/bin/gettext "Invalid Identity installation. Cannot proceed."`
    exit
else
    IS_INSTALL_DIR=`cd $SCRIPT_LOCATION/../../; /bin/pwd`
fi

#-------------------------------------------------------------------------------
#Source utility scripts
#-------------------------------------------------------------------------------
#amutils requires this to be set to source correctly!
INSTALL_FILE_NOT_REQUIRED=true

# import shared utils
#. $IS_INSTALL_DIR/share/bin/amutils
. $IS_INSTALL_DIR/bin/amutils

#import amtune utils
. $IS_INSTALL_DIR/share/bin/amtune/amtune-utils

SCRIPT_BASENAME="$SCRIPT_LOCATION/$SCRIPT_BASENAME : `$DATE +'%D %T'`"

# IS Constants
ADMIN_CLIENT=$IS_INSTALL_DIR/bin/amadmin
LDAPSEARCH=$IS_INSTALL_DIR/bin/ldapsearch

#-------------------------------------------------------------------------------
#Parameter Validation
#-------------------------------------------------------------------------------
if [ $# -lt 2 ]; then
    getUsage
    exit $AMTUNE_INVALID_CMDLINE_PARAMETER
fi

#-------------------------------------------------------------------------------
# Validate Installation Directory
# FIXME: Might be a better solution to determine this with respect to
#        the directory this script is found in (using dirname)
#-------------------------------------------------------------------------------
if [ "$IS_INSTALL_DIR" = "" ] || [ ! -d $IS_INSTALL_DIR ] || [ ! -d $IS_INSTALL_DIR/bin ];  then
    $ECHO `$gettext "Invalid Identity Server installation. Cannot proceed."`
    $ECHO `$gettext "Identity Server installation directory: $IS_INSTALL_DIR"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

#-------------------------------------------------------------------------------
#Validate availability of commands used by the script. Not all of them
#are tested for. But, the few troublesome ones
#-------------------------------------------------------------------------------
if [ ! -f $BC ]; then
    $ECHO `$gettext "Command not found: $BC "`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

#-------------------------------------------------------------------------------
#Validate amtune-env Customizable Enviroment.
#-------------------------------------------------------------------------------
# Assume Review mode if nothing is specified
if [ "$AMTUNE_MODE" = "" ]; then
    AMTUNE_MODE="REVIEW"
fi

#validate AMTUNE_MODE
if [ `$ECHO $AMTUNE_MODE | $GREP -i "REVIEW" | wc -l` -eq 1 ]; then
    AMTUNE_MODE="REVIEW"
elif [ `$ECHO $AMTUNE_MODE | $GREP -i "CHANGE" | wc -l` -eq 1 ]; then
    AMTUNE_MODE="CHANGE"
else
    $ECHO `gettext "AMTUNE_MODE is not valid. Cannot proceed"`
    $ECHO `$gettext "Current AMTUNE_MODE value: $AMTUNE_MODE"`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

#validate AMTUNE_TUNE_* parameters
if [ `$ECHO $AMTUNE_TUNE_OS | $GREP -i "TRUE" | wc -l` -eq 1 ]; then
    AMTUNE_TUNE_OS=true
else
    AMTUNE_TUNE_OS=false
fi
if [ `$ECHO $AMTUNE_TUNE_DS | $GREP -i "TRUE" | wc -l` -eq 1 ]; then
    AMTUNE_TUNE_DS=true
else
    AMTUNE_TUNE_DS=false
fi
if [ `$ECHO $AMTUNE_TUNE_IDENTITY | $GREP -i "TRUE" | wc -l` -eq 1 ]; then
    AMTUNE_TUNE_IDENTITY=true
else
    AMTUNE_TUNE_IDENTITY=false
fi
if [ `$ECHO $AMTUNE_TUNE_WEB_CONTAINER | $GREP -i "TRUE" | wc -l` -eq 1 ]; then
    AMTUNE_TUNE_WEB_CONTAINER=true
else
    AMTUNE_TUNE_WEB_CONTAINER=false
fi

#validate hostname
if [ "$HOSTNAME" = "" ]; then
    $ECHO `gettext "Host name not set. Cannot proceed."`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

#validate domainname
if [ "$DOMAINNAME" = "" ]; then
    $ECHO `gettext "Domain name not set. Cannot proceed."`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

if [ "$WEB_CONTAINER_INSTANCE_NAME" = "" ]; then
    WEB_CONTAINER_INSTANCE_NAME=${HOSTNAME}
fi

if [ "$IS_CONFIG_DIR" = "" ] || [ ! -d $IS_CONFIG_DIR ]; then
    $ECHO `$gettext "Identity Server configuration directory not found. Cannot proceed."`
    $ECHO `$gettext "Identity Server configuration directory: $IS_CONFIG_DIR"`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

#Web Container validation
if [ "$WEB_CONTAINER" = "" ]; then
    $ECHO `$gettext "Web container not specified. Cannot proceed."`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi
webContainerToTune
if [ "$WC_CONFIG" = "" ]; then
    $ECHO `$gettext "Web container specified not valid. Valid Web Containers are WS61, AS7. Cannot proceed."`
    $ECHO `$gettext "Current Web container : $WEB_CONTAINER"`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

if [ "$CONTAINER_BASE_DIR" = "" ] || [ ! -d $CONTAINER_BASE_DIR ]; then
    $ECHO `$gettext "Web Container configuration directory not found. Cannot proceed."`
    $ECHO `$gettext "Current Web Container base directory : $CONTAINER_BASE_DIR"`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

if [ "$CONTAINER_INSTANCE_DIR" = "" ] || [ ! -d $CONTAINER_INSTANCE_DIR ]; then
    $ECHO `$gettext "Web Container instance directory not found. Cannot proceed."`
    $ECHO `$gettext "Current Web Container instance directory : $CONTAINER_INSTANCE_DIR"`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi


if [ 1 -eq 0 ]; then
if [ "$DEFAULT_ORG_PEOPLE_CONTAINER" = "" ]; then
    $ECHO `$gettext "Default Org's People Container is empty. Cannot proceed."`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi
fi

if [ "$ADMIN_CLIENT" = "" ] || [ ! -f $ADMIN_CLIENT ]; then
    $ECHO `$gettext "Identity Server Admin Client Utility not found. Cannot proceed."`
    $ECHO `$gettext "Current Admin Client Utility: $ADMIN_CLIENT"`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

setAMConfigPropertyFile

if [ "$AMCONFIG_PROPERTY_FILE" = "" ] || [ ! -f $AMCONFIG_PROPERTY_FILE ]; then
    $ECHO `$gettext "Identity Server configuration file not found. Cannot proceed."`
    $ECHO `$gettext "Identity Server configuration file : $AMCONFIG_PROPERTY_FILE"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

if [ "$LDAPSEARCH" = "" ] || [ ! -f $LDAPSEARCH ]; then
    $ECHO `$gettext "ldapsearch command line not found. Cannot proceed."`
    $ECHO `$gettext "Current ldapsearch Utility: $LDAPSEARCH"`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

DS_HOST=`getConfigEntry "com.iplanet.am.directory.host"`
DS_PORT=`getConfigEntry "com.iplanet.am.directory.port"`

if [ "$DS_HOST" = "" ] || [ "$DS_PORT" = "" ] || 
    [ "$RAM_DISK" = "" ] || [ "$DIRMGR_UID" = "" ] || [ "$DIRMGR_PASSWORD" = "" ]; then
    #FIXME: message need to be expanded for each case
    $ECHO `$gettext "Directory Server configuration invalid. Cannot proceed."`
    $ECHO `$gettext "You may need to customize the following file appropriately: amtune-env"`
    exit $AMTUNE_INVALID_ENVIRON_SETTING
fi

debug_dir=`getConfigEntry "com.iplanet.services.debug.directory"`
if [ "$AMTUNE_DEBUG_FILE_PREFIX" = "" ]; then
    DEBUG_FILE=/dev/null
else
    DEBUG_FILE=$AMTUNE_DEBUG_FILE_PREFIX-`$DATE +'%Y%m%d'`-$$

    #if the debug directory is specified in AMConfig.properties, then place the debug file there
    #if debug directory is not specified or not found, create the Debug file in the current directory
    if [ "$debug_dir" != "" ]; then
        if [ -d $debug_dir ]; then
            DEBUG_FILE=$debug_dir/$AMTUNE_DEBUG_FILE_PREFIX-`$DATE +'%Y%m%d'`-$$
        fi
    fi
    #Make sure you can write to the debug file
    $TOUCH $DEBUG_FILE 1> /dev/null 2>&1
    if [ $? -eq 1 ]; then
        $ECHO `$gettext "Cannot create amtune debug file. Cannot proceed."`
        $ECHO `$gettext "Debug file location: $DEBUG_FILE"`
        exit $AMTUNE_INVALID_ENVIRON_SETTING
    fi

    $ECHO `$gettext "Debug information log can be found in file: $DEBUG_FILE"`
    $TAIL -1f $DEBUG_FILE &
fi

#session parameters to be touched? Default is not to touch it
if [ `$ECHO $AMTUNE_DONT_TOUCH_SESSION_PARAMETERS | $GREP -i "TRUE" | wc -l` -eq 1 ]; then
    AMTUNE_DONT_TOUCH_SESSION_PARAMETERS=true
else
    AMTUNE_DONT_TOUCH_SESSION_PARAMETERS=false
fi
#validate the session values
if [ "$AMTUNE_DONT_TOUCH_SESSION_PARAMETERS" = "true" ]; then
    if [ "$AMTUNE_SESSION_MAX_SESSION_TIME_IN_MTS" = "" ]; then
        AMTUNE_SESSION_MAX_SESSION_TIME_IN_MTS=60
    fi
    if [ "$AMTUNE_SESSION_MAX_IDLE_TIME_IN_MTS" = "" ]; then
        AMTUNE_SESSION_MAX_IDLE_TIME_IN_MTS=10
    fi
    if [ "$AMTUNE_SESSION_MAX_CACHING_TIME_IN_MTS" = "" ]; then
        AMTUNE_SESSION_MAX_CACHING_TIME_IN_MTS=2
    fi
fi


$ECHO $CHAPTER_SEP                                          1>>$DEBUG_FILE 2>&1
$ECHO $SCRIPT_BASENAME                                      1>>$DEBUG_FILE 2>&1
$ECHO $CHAPTER_SEP                                          1>>$DEBUG_FILE 2>&1
$ECHO "Initializing..."                                     1>>$DEBUG_FILE 2>&1

$ECHO $LINE_SEP                                             1>>$DEBUG_FILE 2>&1

# check system env
$ECHO "Checking System Environment..."                      1>>$DEBUG_FILE 2>&1
check_env 

# check for root
$ECHO "Checking User..."                                    1>>$DEBUG_FILE 2>&1
check_root_user 

# Print mode and components to tune
$ECHO $LINE_SEP                                             1>>$DEBUG_FILE 2>&1
$ECHO "amtune Information..."                               1>>$DEBUG_FILE 2>&1     
$ECHO $LINE_SEP                                             1>>$DEBUG_FILE 2>&1
$ECHO "amtune Mode      : $AMTUNE_MODE"                     1>>$DEBUG_FILE 2>&1
$ECHO "OS               : $AMTUNE_TUNE_OS"                  1>>$DEBUG_FILE 2>&1
$ECHO "Identity         : $AMTUNE_TUNE_IDENTITY"            1>>$DEBUG_FILE 2>&1
$ECHO "Directory        : $AMTUNE_TUNE_DS"                  1>>$DEBUG_FILE 2>&1
$ECHO "Web Container    : $AMTUNE_TUNE_WEB_CONTAINER"       1>>$DEBUG_FILE 2>&1


$ECHO $LINE_SEP                                             1>>$DEBUG_FILE 2>&1
$ECHO "Detecting System Environment..."                     1>>$DEBUG_FILE 2>&1
$ECHO $LINE_SEP                                             1>>$DEBUG_FILE 2>&1

numCPUS=`getNumberOfCPUS`
$ECHO "Number of CPUs in the system:" $numCPUS              1>>$DEBUG_FILE 2>&1
if [ "$numCPUS" = "" ]; then 
    $ECHO `gettext "Unable to obtain available CPUs. Cannot proceed."`
    exit
fi


#acceptorThreads=`$ECHO "scale=0; $numCPUS * $AMTUNE_WS_ACCEPTOR_PER_CPU_MULTIPLIER" | $BC`
acceptorThreads=$AMTUNE_NUM_ACCEPTOR_THREADS
$ECHO "WS Acceptor Threads:" $acceptorThreads               1>>$DEBUG_FILE 2>&1


memAvail=`getSystemMemory`
$ECHO "Memory Available (MB): " $memAvail                        1>>$DEBUG_FILE 2>&1
if [ "$memAvail" = "" ]; then 
    $ECHO `gettext "Unable to obtain available memory. Cannot proceed."`
    exit
fi

if [ "$OSTYPE" = "Linux" ]; then
    amtuneMaxMemoryToUseInMB=$AMTUNE_MAX_MEMORY_TO_USE_IN_MB_LINUX
elif  [ "$OSTYPE" = "SunOS" ]; then
    amtuneMaxMemoryToUseInMB=$AMTUNE_MAX_MEMORY_TO_USE_IN_MB_SOLARIS
else
    amtuneMaxMemoryToUseInMB=$AMTUNE_MAX_MEMORY_TO_USE_IN_MB_DEFAULT
fi

memToUse=` $ECHO "
scale=0
m=$memAvail * $AMTUNE_PCT_MEMORY_TO_USE / 100
if ( m > $amtuneMaxMemoryToUseInMB ) {
$amtuneMaxMemoryToUseInMB
}
if ( m <= $amtuneMaxMemoryToUseInMB ) {
m
}
" | $BC `
$ECHO "Memory to Use (MB):" $memToUse                            1>>$DEBUG_FILE 2>&1

if [ "$memToUse" = "" ]; then 
    $ECHO `gettext "Unable to compute memory requirements. Cannot proceed."`
    exit
fi


memEnough=` $ECHO "
if ($memToUse >= $AMTUNE_MIN_MEMORY_TO_USE_IN_MB) {
1
}
" | $BC`

if [ "$memEnough" = "1" ]; then
    $ECHO "There is enough memory."                         1>>$DEBUG_FILE 2>&1
else
    $ECHO `gettext "There is not enough memory."`
    exit
fi

$ECHO $LINE_SEP                                             1>>$DEBUG_FILE 2>&1
$ECHO "Calculating Tuning Parameters..."                    1>>$DEBUG_FILE 2>&1
$ECHO $LINE_SEP                                             1>>$DEBUG_FILE 2>&1

maxHeapSize=` $ECHO "
scale=0
$memToUse * $AMTUNE_MEM_AVAIL_FOR_JAVA
" | $BC `
$ECHO "Max heap size:" $maxHeapSize                         1>>$DEBUG_FILE 2>&1 

maxNewSize=`$ECHO "scale=0; $maxHeapSize * $AMTUNE_MEM_MAX_NEW_SIZE" | $BC`
$ECHO "Max new size:" $maxNewSize                           1>>$DEBUG_FILE 2>&1

maxPermSize=`$ECHO "scale=0; $maxHeapSize * $AMTUNE_MEM_MAX_PERM_SIZE" | $BC`
maxPermSize=`roundOf $maxPermSize 1`
$ECHO "Max perm size:" $maxPermSize                         1>>$DEBUG_FILE 2>&1

cacheSize=`$ECHO "scale=0; $maxHeapSize * $AMTUNE_MEM_CACHES_SIZE" | $BC`
$ECHO "Cache size:" $cacheSize                              1>>$DEBUG_FILE 2>&1

sdkCacheSize=`$ECHO "scale=0; $cacheSize * $AMTUNE_MEM_SDK_CACHE_SIZE" | $BC`
$ECHO "SDK Cache size:" $sdkCacheSize                       1>>$DEBUG_FILE 2>&1

numSDKCacheEntries=`$ECHO "scale=0; $sdkCacheSize * 1024 / $AMTUNE_AVG_PER_ENTRY_CACHE_SIZE_IN_KB" | $BC`
$ECHO "Number of SDK Cache Entries:" $numSDKCacheEntries    1>>$DEBUG_FILE 2>&1

sessionCacheSize=`$ECHO "scale=0; $cacheSize * $AMTUNE_MEM_SESSION_CACHE_SIZE" | $BC`
$ECHO "Session Cache size:" $sessionCacheSize               1>>$DEBUG_FILE 2>&1

numSessions=`$ECHO "scale=0; $sessionCacheSize * 1024 / $AMTUNE_AVG_PER_SESSION_SIZE_IN_KB" | $BC`
$ECHO "Number of Session Cache Entries:" $numSessions       1>>$DEBUG_FILE 2>&1

maxThreads=`$ECHO "scale=10; m=$AMTUNE_MAX_NUM_THREADS; scale=0; $maxHeapSize * m" | $BC`

maxThreads=`removeDecimals $maxThreads`
$ECHO "Max threads:" $maxThreads                            1>>$DEBUG_FILE 2>&1

numRQThrottle=`$ECHO "scale=0; $maxThreads * $AMTUNE_WS_RQTHROTTLE_THREADS " | $BC`
$ECHO "RQThrottle:" $numRQThrottle                          1>>$DEBUG_FILE 2>&1

numLdapAuthThreads=`$ECHO "scale=0; $maxThreads * $AMTUNE_IS_AUTH_LDAP_THREADS" | $BC`
$ECHO "LDAP Auth Threads:" $numLdapAuthThreads              1>>$DEBUG_FILE 2>&1

numSMLdapThreads=`$ECHO "scale=0; $maxThreads * $AMTUNE_IS_SM_LDAP_THREADS" | $BC`
$ECHO "SM LDAP Threads:" $numSMLdapThreads                  1>>$DEBUG_FILE 2>&1

numNotificationThreads=`$ECHO "scale=0; $maxThreads * $AMTUNE_IS_NOTIFICATION_THREADS" | $BC`
$ECHO "Notification Threads:" $numNotificationThreads       1>>$DEBUG_FILE 2>&1

numNotificationQueue=`$ECHO "scale=0; $numNotificationThreads * $AMTUNE_IS_NOTIFICATION_QUEUE_SIZE_PER_THREAD" | $BC`
$ECHO "Notification Queue Size:" $numNotificationQueue      1>>$DEBUG_FILE 2>&1

$ECHO $PARA_SEP                                             1>>$DEBUG_FILE 2>&1


INIT_STATUS="INIT_COMPLETE"
