#!/bin/sh

# Copyright  2004 Sun Microsystems, Inc. All rights reserved. 
# 
# Sun Microsystems, Inc. has intellectual property rights relating to
# technology embodied in the product that is described in this document.
# In particular, and without limitation, these intellectual property rights
# may include one or more of the U.S. patents listed at
# http://www.sun.com/patents and one or more additional patents or pending
# patent applications in the U.S. and in other countries.
# 
# U.S. Government Rights - Commercial software. Government users are subject
# to the Sun Microsystems, Inc. standard license agreement and applicable
# provisions of the FAR and its supplements.
# 
# Use is subject to license terms. 
# 
# This distribution may include materials developed by third parties. Sun,
# Sun Microsystems, the Sun logo, Java and Sun[tm] ONE are trademarks or
# registered trademarks of Sun Microsystems, Inc. in the U.S. and other
# countries. 
# 
# Copyright  2004 Sun Microsystems, Inc. Tous droits rservs. Sun
# Microsystems, Inc. dtient les droits de proprit intellectuels relatifs
#  la technologie incorpore dans le produit qui est dcrit dans ce document.
# En particulier, et ce sans limitation, ces droits de proprit
# intellectuelle peuvent inclure un ou plus des brevets amricains lists
#  l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires
# ou les applications de brevet en attente aux Etats - Unis et dans les
# autres pays.
# 
# L'utilisation est soumise aux termes du contrat de licence.
# 
# Cette distribution peut comprendre des composants dvelopps par des
# tierces parties.
# 
# Sun, Sun Microsystems, le logo Sun, Java et Sun[tm] ONE sont des marques
# de fabrique ou des marques dposes de Sun Microsystems, Inc. aux
# Etats-Unis et dans d'autres pays.


################################################################################
#===============================================================================
# amtune Functions
#===============================================================================

#-------------------------------------------------------------------------------
# Function      :   getSystemMemory
# Parameters    :   -None-
# Output        :   Returns memory (RAM) available in MB in a Solaris system
# Description   :   This function returns memory available in Megabytes in a Solaris
#                   box as reported by prtconf command
#-------------------------------------------------------------------------------
getSystemMemory() {
    if [ "$OSTYPE" = "Linux" ]; then
        lin_mem_in_bytes=`$GREP "Mem:" /proc/meminfo | $AWK '{print $2}'`
        $ECHO " scale=0; $lin_mem_in_bytes / 1024 / 1024 " | $BC
    else
        /usr/sbin/prtconf | $GREP Mem | $AWK '{print $3}'
    fi
}

#-------------------------------------------------------------------------------
# Function      :   getNumberOfCPUS
# Parameters    :   -None-
# Output        :   Returns number of "on-line" CPUs in a Solaris system   
# Description   :   This function returns the number of on-line CPUs in a Solaris
#                   box as reported by psrinfo command
#-------------------------------------------------------------------------------
getNumberOfCPUS() {
    if [ "$OSTYPE" = "Linux" ]; then
        $GREP processor /proc/cpuinfo | $WC -l
    else
        /usr/sbin/psrinfo | $GREP -i "on-line" | $WC -l 
    fi
}

#-------------------------------------------------------------------------------
# Function      :   removeDecimals
# Parameters    :   1. number input (most likely with decimals)
# Output        :   Returns a whole number stripping out decimals
# Description   :   This function returns a whole number stripping out decimals
#                   from the input number. The call does not round the input 
#                   values
#-------------------------------------------------------------------------------
removeDecimals() {
value=$1

z=`$ECHO "
scale=0
$value/1
" | $BC`
$ECHO $z
}

#-------------------------------------------------------------------------------
# Function      :   roundOf
# Parameters    :   1. number input (with or without decimals)
#                   2. roundoff - How many digits from the right to round of
# Output        :   Returns a rounded off number 
# Description   :   This function returns a rounded off number derived from
#                   the input number. 
#                   - Round off works on both numbers with decimals
#                   and numbers without decimals. 
#                   - Rounds off numbers to the position passed in as the second
#                   parameter
#                   - If you would like to round off only the left of the decimal,
#                   then you will need to call removeDecimals first and then call
#                   roundOf.
#-------------------------------------------------------------------------------
roundOf() {
value=$1
roundoff=$2

z=`$ECHO "
a=length ( $value )
if ( a > $roundoff ) {
    scale=scale( $value)
    ($value / 10 ^ $roundoff) * (10 ^ $roundoff)
}" | $BC`
$ECHO $z
}

#-------------------------------------------------------------------------------
# Function      : test_bc_dc
# Description   : Just some testing routine...
#-------------------------------------------------------------------------------
test_bc_dc() {
$ECHO "bc/dc command testing..."
x=`$ECHO 'scale=0; 104348/33215' | $BC`
$ECHO "1:" $x
y=`$ECHO "length ( $x ) " | $BC`
$ECHO "Length of 1:" $y
z=`$ECHO "scale ( $x ) " | $BC`
$ECHO "Scale of 1:" $z

x=`$ECHO 'scale=10; 104348/33215*1000000' | $BC`
$ECHO "2:" $x
y=`$ECHO "length ( $x ) " | $BC`
$ECHO "Length of 2:" $y
z=`$ECHO "scale ( $x ) " | $BC`
$ECHO "Scale of 2:" $z
i=`roundOf $x 4`
$ECHO "RoundOff:" $i

x=`printf "%s" '1000' `
$ECHO "3:" $x
y=`$ECHO "length ( $x ) " | $BC`
$ECHO "Length of 3:" $y
z=`$ECHO "scale ( $x ) " | $BC`
$ECHO "Scale of 3:" $z

x=`printf "%s\n" 'scale = 10; 104348/33215'  | $BC`
$ECHO "4:" $x
y=`$ECHO "length ( $x ) " | $BC`
$ECHO "Length of 4:" $y
z=`$ECHO "scale ( $x ) " | $BC`
$ECHO "Scale of 4:" $z
i=`roundOf $x 4`
$ECHO "RoundOff:" $i

x=`$ECHO "
scale=0
104348*1000000/33215
" | $BC`
$ECHO "5:" $x
y=`$ECHO "length ( $x ) " | $BC`
$ECHO "Length of 5:" $y
z=`$ECHO "scale ( $x ) " | $BC`
$ECHO "Scale of 5:" $z
i=`roundOf $x 3`
$ECHO "RoundOff:" $i

x=`printf "%s\n" 'scale = 0; 100/100'  | $BC`
$ECHO "6:" $x
y=`$ECHO "length ( $x ) " | $BC`
$ECHO "Length of 6:" $y
z=`$ECHO "scale ( $x ) " | $BC`
$ECHO "Scale of 6:" $z

$ECHO "
scale = 20
define e(x){
auto a, b, c, i, s
a = 1
b = 1
s = 1
for(i=1; 1==1; i++){
a = a*x
b = b*i
c = a/b
if(c == 0) return(s)
s = s+c
}
}
for (i = 1; i <= 10; ++i) { e(i) }
" | $BC
}


#-------------------------------------------------------------------------------
# Function      :   webContainerToTune
# Parameters    :   -None-
# Output        :   Sets a variable WC_CONFIG 
# Description   :   Identifies what container the identity is installed on and
#                   returns the script name to run for tuning the container
#-------------------------------------------------------------------------------
webContainerToTune()
{
    if [ "$WEB_CONTAINER" = "WS61" ]; then
        WC_CONFIG=./amtune-ws61
    elif [ "$WEB_CONTAINER" = "AS7" ]; then
        WC_CONFIG=./amtune-as7
    else
        WC_CONFIG=
    fi
}

#-------------------------------------------------------------------------------
# Function      :   getEntry
# Parameters    :   1. Entry to fetch
# Output        :   Returns the the config entry value read from AMConfig.properties
# Description   :   This function reads a configuration entry from AMConfig.properties
#-------------------------------------------------------------------------------
getEntry() {
    property=$1
    file=$2

    if [ "$property" = "" ]; then
        return
    fi

    if [ "$file" = "" ] || [ ! -f $file ]; then
        return
    fi

    propStr=`$GREP $property $file`
    if [ "$propStr" = "" ]; then
        return
    fi

    $ECHO $propStr | $CUT -f2- -d"="
    return
}

#-------------------------------------------------------------------------------
# Function      :   getConfigEntry
# Parameters    :   1. Config Entry to fetch
# Output        :   Returns the the config entry value read from AMConfig.properties
# Description   :   This function reads a configuration entry from AMConfig.properties
#-------------------------------------------------------------------------------
getConfigEntry() {
    # Dont have to check for existence of AMConfig. Its already being done in amtune-env
    property=$1
    if [ "$property" = "" ]; then
        return
    fi
    
    setAMConfigPropertyFile

    propStr=`$GREP $property $AMCONFIG_PROPERTY_FILE`
    if [ "$propStr" = "" ]; then
        return
    fi

    $ECHO $propStr | $CUT -f2- -d"="
    return
}

#-------------------------------------------------------------------------------
# Function      :   setAMConfigPropertyFile
# Parameters    :   <none>
# Output        :   Returns the AMConfig.properties file name
#                   AMConfig.properties coule be instance specific
# Description   :
#-------------------------------------------------------------------------------
setAMConfigPropertyFile() {

    if [ "$IS_INSTANCE_NAME" != "" ]; then
        AMCONFIG_PROPERTY_FILE=$IS_CONFIG_DIR/AMConfig-$IS_INSTANCE_NAME.properties
    elif [ "$WEB_CONTAINER_INSTANCE_NAME" != "" ]; then
        AMCONFIG_PROPERTY_FILE=$IS_CONFIG_DIR/AMConfig-$WEB_CONTAINER_INSTANCE_NAME.properties
    fi

    if [ ! -f $AMCONFIG_PROPERTY_FILE ]; then
        AMCONFIG_PROPERTY_FILE=$IS_CONFIG_DIR/AMConfig.properties
    fi

}

getMagnusEntry() {
    entry_file=$1
    entry_key=$2
   
    entry_value=`$GREP -i "$entry_key " $entry_file`
    if [ "$entry_value" = "" ]; then
        $ECHO "<No value set>"
        return
    fi

    $ECHO $entry_value | $AWK '{print $2}'
    return
}

getServerXMLJVMOptionEntry() {
    entry_file=$1
    entry_key='\'$2
    jvmoption_key=$3

    if [ "$jvmoption_key" = "" ]; then
        jvmoption_key="JVMOPTIONS"
    fi
    
    entry_value=`$GREP -i $jvmoption_key $entry_file | $GREP -i "$entry_key"`
    if [ "$entry_value" = "" ]; then
        $ECHO "<No value set>"
        return
    fi

    $ECHO $entry_value | $NAWK ' FS= ">" {print $2}' | $NAWK ' FS="<" {print $1}'
    return
}

get_token_in_line(){
    file=$1
    match=$2
    token=$3

    #step1: grep for classpath suffix in server.xml
    orig_line=`grep $match $file`

    if [ "$orig_line" = "" ]; then
        $ECHO "<No value set>"
        return
    fi

    #step2: Get the number of tokens in the line
    number_of_tokens=`echo $orig_line | nawk ' { print NF } '`

    #step3: Get the value for the token
    count=1
    newline=""
    while [ $count -le $number_of_tokens ]
    do
        currentToken=`echo $orig_line | cut -f$count -d " "`
        desiredTokenStr=`echo $currentToken | cut -f$count -d " " | grep $token`
        if [ "$desiredTokenStr" != "" ]; then
            desiredTokenValue=`echo $desiredTokenStr | nawk ' BEGIN { FS="=" } { print $2 } ' | cut -f2 -d "\""`
            if [ "$desiredTokenValue" = "" ]; then
                echo "<Empty Value>"
            else
                echo $desiredTokenValue
            fi
            return
       fi
       count=`expr $count + 1`
    done
    $ECHO "<No value set>"
    return
}

#-------------------------------------------------------------------------------
# Function      :   setServerConfigXMLFile
# Parameters    :   <none>
# Output        :   Returns the serverconfig.xml file name
#                   Currently, serverconfig.xml file could be instance specific
# Description   :
#-------------------------------------------------------------------------------
setServerConfigXMLFile() {

    if [ "$IS_INSTANCE_NAME" != "" ]; then
        SERVERCONFIG_XML_FILE=$IS_CONFIG_DIR/serverconfig-$IS_INSTANCE_NAME.xml
    elif [ "$WEB_CONTAINER_INSTANCE_NAME" != "" ]; then
        SERVERCONFIG_XML_FILE=$IS_CONFIG_DIR/serverconfig-$WEB_CONTAINER_INSTANCE_NAME.xml
    fi

    if [ ! -f $SERVERCONFIG_XML_FILE ]; then
        SERVERCONFIG_XML_FILE=$IS_CONFIG_DIR/serverconfig.xml
    fi

}

#===============================================================================
# LDAP related functions
#===============================================================================
getNumberOfWorkerThreads() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config" -s "base" "(objectclass=*)" "nsslapd-threadnumber" | $GREP "nsslapd-threadnumber:" | $CUT -f2 -d":"`
}

getAccessLogStatus() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config" -s "base" "(objectclass=*)" "nsslapd-accesslog-logging-enabled" | $GREP "nsslapd-accesslog-logging-enabled:" | $CUT -f2 -d":"`
}

getInstanceDir() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config" -s "base" "(objectclass=*)" "nsslapd-instancedir" | $GREP "nsslapd-instancedir:" | $CUT -f2 -d":"`
}

getDBDirectory() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config" "(nsslapd-suffix=$ROOT_SUFFIX)" "nsslapd-directory" | $GREP "nsslapd-directory:" | $CUT -f2 -d":"`
}

getDBDN() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config" "(nsslapd-suffix=$ROOT_SUFFIX)" "dn" | $GREP "dn:" | $CUT -f2 -d":"`
}

getDBEntryCacheSize() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config" "(nsslapd-suffix=$ROOT_SUFFIX)" "nsslapd-cachememsize" | $GREP "nsslapd-cachememsize:" | $CUT -f2 -d":"`
}

getDBCacheSize() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config,cn=ldbm database,cn=plugins,cn=config" -s "base" "(objectclass=*)" "nsslapd-dbcachesize" | $GREP "nsslapd-dbcachesize:" | $CUT -f2 -d":"`
}

getDBLocation() {
        $ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config,cn=ldbm database,cn=plugins,cn=config" -s "base" "(objectclass=*)" "nsslapd-directory" | $GREP "nsslapd-directory:" | $CUT -f2 -d":"`
}

getDBHomeLocation() {
	$ECHO `$LDAPSEARCH -h $DS_HOST -p $DS_PORT -D "$DIRMGR_UID" -w "$DIRMGR_PASSWORD" -b "cn=config,cn=ldbm database,cn=plugins,cn=config" -s "base" "(objectclass=*)" "nsslapd-db-home-directory" | $GREP "nsslapd-db-home-directory:" | $CUT -f2 -d":"`
}

#===============================================================================
# Environment Constants
#-------------------------------------------------------------------------------
# Its not recommended to modify any of the following env variables
# But, in certain circumstances, you might have to change these
#===============================================================================
# Solaris var's

PATH=/bin:/usr/bin:/sbin:/usr/sbin
if [ "$OSTYPE" = "Linux" ]; then
	LD_LIBRARY_PATH=$IS_INSTALL_DIR/ldaplib/ldapsdk:/opt/sun/private/lib
else
	LD_LIBRARY_PATH=$IS_INSTALL_DIR/ldaplib/ldapsdk:/usr/lib/mps/secv1
fi
export PATH LD_LIBRARY_PATH

OSTYPE=`/bin/uname -s`

ECHO=/bin/echo
DIRNAME=/bin/dirname
BASENAME=/bin/basename
RM=/bin/rm
CUT=/bin/cut
DATE=/bin/date

CP=/bin/cp
SED=/bin/sed
AWK=/bin/awk
NAWK=/bin/nawk
LS=/bin/ls
NETSTAT=/bin/netstat
CAT=/bin/cat
CP="/bin/cp -p"
gettext=/bin/gettext
OPEN='('
CLOSE=')'
OMIT='\c'
MKDIR=/bin/mkdir
GREP=/bin/grep
BC=/bin/bc
TAIL=/bin/tail
TOUCH=/bin/touch
WC=/bin/wc
NDD=/usr/sbin/ndd
TAR=/bin/tar

if [ "$OSTYPE" = "Linux" ]
then
    NAWK=/bin/awk
    ECHO="/bin/echo -e"
    BC=/usr/bin/bc
    TAIL=/usr/bin/tail
    DIRNAME=/usr/bin/dirname
    WC=/usr/bin/wc
fi

LINE_SEP="---------------------------------------------------------------------"
PARA_SEP="====================================================================="
CHAPTER_SEP="#####################################################################"
