HEX
Server: Apache/2.4.34 (Red Hat) OpenSSL/1.0.2k-fips
System: Linux WORDPRESS 3.10.0-1160.118.1.el7.x86_64 #1 SMP Thu Apr 4 03:33:23 EDT 2024 x86_64
User: digital (1020)
PHP: 7.2.24
Disabled: NONE
Upload Files
File: //opt/OV/lbin/configure/HPOvPerfAgt/configure.sh
#!/bin/sh
# 
# @(#)BegWS :1.0
# @(#)CR    :(c) Copyright 2017 Hewlett-Packard Enterprise Development Company, L.P.
# @(#)Name  :HPE Software Performance Component
# @(#)Ver   :12.05.006
# @(#)FileN :configure.sh
# @(#)FileV :12.05.006
# @(#)Rtype :Released
# @(#)CBID  :2017-11-16_1500
# @(#)OS    :Linux
# @(#)OSV   :2.6
# @(#)Arch  :x64
# @(#)Bits  :64
# @(#)Desc  :HP Software
# @(#)Patch :
# @(#)Build :0000
# @(#)EndWS :
# 
#!/bin/sh

# include shell libraries

# Set bash built-in echo command to interpret special (backslash) characters.
shopt -s xpg_echo

if [ -r /tmp/OVCSL_DEBUG_VERBOSE ]; then
    set -x
fi

# Common constants
TRUE=0
FALSE=1

# Column after which OvCslEcho will do a line break in the formated output of
# the given message.
OVCSL_ECHO_WIDTH=80

# Error return codes
# Reserved for custom use = 1-100
OVCSL_ERROR_UNKNOWN="101"
OVCSL_ERROR_USAGE="102"
OVCSL_ERROR_PERMISSION_DENIED="103"
OVCSL_ERROR_TYPE_MISMATCH="104"
OVCSL_ERROR_DISK_SPACE="105"
OVCSL_ERROR_FILE_NOT_FOUND="106"
OVCSL_ERROR_OPENING_FILE="107"
OVCSL_ERROR_WRITING_FILE="108"
OVCSL_ERROR_READING_FILE="109"
OVCSL_ERROR_DELETING_FILE="200"
OVCSL_ERROR_MOVING_FILE="201"
OVCSL_ERROR_COPYING_FILE="202"
OVCSL_ERROR_FILE_NOT_REGULAR="203"
OVCSL_ERROR_DIR_NOT_FOUND="204"
OVCSL_ERROR_INVALID_PATH="205"
OVCSL_ERROR_NETWORK="206"
OVCSL_ERROR_FILE_NOT_EXECUTABLE="207"

# Error message catalog
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_UNKNOWN]="Unknown error"
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_USAGE]="Incorrect usage "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_PERMISSION_DENIED]="Permission denied "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_TYPE_MISMATCH]="Type mismatch "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_DISK_SPACE]="Insufficient disk space"
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_FILE_NOT_FOUND]="File not found"
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_OPENING_FILE]="Unable to open file "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_WRITING_FILE]="Unable to write to file "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_READING_FILE]="Unable to read from file "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_DELETING_FILE]="Unable to delete file"
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_MOVING_FILE]="Unable to move file"
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_COPYING_FILE]="Unable to copy file"
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_FILE_NOT_REGULAR]="File is not a regular file "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_DIR_NOT_FOUND]="Directory not found "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_INVALID_PATH]="Invalid path "
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_NETWORK]="Network error"
OVCSL_ERROR_MESSAGES[$OVCSL_ERROR_FILE_NOT_EXECUTABLE]="File is not executable"

# System runlevels
OVCSL_RC_NO_NETWORK="2"
if [ -f /etc/debian_version ]
then
    OVCSL_RC_WITH_NETWORK="2 3 4 5"
else
    OVCSL_RC_WITH_NETWORK="3 4 5"
fi

# File extension of backup copies
OVCSL_FILE_BACKUP_EXT="ov_backup"

#
# OpenView directories
#

OVCSL_OV_ROOT="/opt/OV"
OVCSL_OV_DATA="/var/opt/OV"
OVCSL_OV_BIN="/opt/OV/bin"
OVCSL_OV_LIB="/opt/OV/lib"
OVCSL_OV_LBIN="/opt/OV/lbin"
OVCSL_OV_WWW="/opt/OV/www"
OVCSL_OV_WWW_CGI_BIN="/opt/OV/www/cgi-bin"
OVCSL_OV_WWW_HTDOCS="/opt/OV/www/htdocs"
OVCSL_OV_WWW_WEBSTART="/opt/OV/www/webstart"
OVCSL_OV_JAVA="/opt/OV/java"
OVCSL_OV_REL_NOTES="/opt/OV/ReleaseNotes"
OVCSL_OV_NEW_CONFIG="/opt/OV/newconfig"
OVCSL_OV_INCLUDE="/opt/OV/include"
OVCSL_OV_CONTRIB="/opt/OV/contrib"
OVCSL_OV_NLS="/opt/OV/nls"
OVCSL_OV_EXAMPLES="/opt/OV/examples"
OVCSL_OV_PACKAGES="/opt/OV/packages"
OVCSL_OV_INSTALL="/opt/OV/install"
OVCSL_OV_ROM="/opt/OV/rom"
OVCSL_OV_SUPPORT="/opt/OV/support"
OVCSL_OV_NON_OV="/opt/OV/nonOV"
OVCSL_OV_LICENSES="/opt/OV/license-agreements"

OVCSL_OV_DATA_SHARE="/var/opt/OV/share"
OVCSL_OV_DATA_SHARE_CONF="/var/opt/OV/share/conf"
OVCSL_OV_DATA_CONF="/var/opt/OV/conf"
OVCSL_OV_DATA_LOG="/var/opt/OV/log"
OVCSL_OV_DATA_DATABASES="/var/opt/OV/datafiles" # DEPRECATED (OvCsl02.00): Use OVCSL_OV_DATA_DATAFILES instead
OVCSL_OV_DATA_DATAFILES="/var/opt/OV/datafiles"
OVCSL_OV_DATA_CERTIFICATES="/var/opt/OV/certificates"
OVCSL_OV_DATA_TMP="/var/opt/OV/tmp"
OVCSL_OV_DATA_IMAGES="/var/opt/OV/images"
OVCSL_OV_DATA_WWW="/var/opt/OV/www"

# Log files
OVCSL_TRACE_FILE="$OVCSL_OV_DATA_LOG/OvCsl.trace"
OVCSL_LOG_FILE="$OVCSL_OV_DATA_LOG/OvCsl.log"

# Maximum size of the log files in KB before they will be rotated.
OVCSL_TRACE_FILE_SIZE=2048
OVCSL_LOG_FILE_SIZE=2048

#
# External system tools
#

OVCSL_SH="/bin/sh"
OVCSL_AWK="awk"
OVCSL_SED="sed"
OVCSL_GREP="grep"
OVCSL_CUT="cut"
OVCSL_TOUCH="touch"
OVCSL_CHMOD="/bin/chmod"
OVCSL_CHOWN="/bin/chown"
OVCSL_MV="/bin/mv"
OVCSL_CP="/bin/cp -f"
OVCSL_CD="cd"
OVCSL_LS="ls"
OVCSL_RM="/bin/rm -f"
OVCSL_RMDIR="/bin/rmdir"
OVCSL_MKDIR="/bin/mkdir"
OVCSL_LN="/bin/ln -f"
OVCSL_CAT="/bin/cat"
OVCSL_MORE="/bin/more"
OVCSL_UNAME="/bin/uname"
OVCSL_TRUE="/bin/true"
OVCSL_FALSE="/bin/false"
OVCSL_EXPR="/usr/bin/expr"
OVCSL_ECHO="echo -e"
OVCSL_COMPRESS="/usr/bin/compress "
OVCSL_PS="/bin/ps"
OVCSL_YPWHICH="/usr/bin/ypwhich"
OVCSL_YPCAT="/usr/bin/ypcat"
OVCSL_NISCAT="/usr/bin/niscat"
OVCSL_ID="/usr/bin/id"
OVCSL_TAR="/bin/tar"
OVCSL_USERADD="/usr/sbin/useradd"
OVCSL_USERDEL="/usr/sbin/userdel"
OVCSL_GROUPADD="/usr/sbin/groupadd"
OVCSL_GROUPDEL="/usr/sbin/groupdel"
OVCSL_WC="/usr/bin/wc"
OVCSL_SU="/bin/su"
OVCSL_SG="/usr/bin/sg"
OVCSL_FMT="/usr/bin/fmt"
OVCSL_BASENAME="basename"
OVCSL_FIND="/usr/bin/find"

# Platform specific tools
OVCSL_RPM="/bin/rpm"
OVCSL_DPKG="/usr/bin/dpkg" # Debian only!

## FUNCTION:    OvCslStrTrim
## DESCRIPTION: Removes leading and trailing blanks and tabs from a string.
## PARAMETERS:  $1: Source string
## RETURN VAL:
## RETURN ECHO: Trimmed string.

OvCslStrTrim()
{
    typeset wspaces=`echo " \t\v"`
    echo "$1" | sed -e "s/^[$wspaces]*//" -e "s/[$wspaces]*$//"
}

## FUNCTION:    OvCslFilterEmptyLines
## DESCRIPTION: Filters empty lines from a string that is pipped through this
##              function.
## PARAMETERS:  - None -
## RETURN VAL:
## RETURN ECHO: Filtered string without empty lines.

OvCslFilterEmptyLines()
{
    typeset wspaces=`echo -e " \t\v"`
    typeset line=""
    while read line
    do
        echo $line | grep -qs "^[$wspaces]*$" || echo $line
    done
}

## FUNCTION:     OvCslStrMsgFmt
## DESCRIPTION:  Format a message based on the given message type. The message
##               will be indented with certain keywords and a line break will be
##               done according to the OVCSL_ECHO_WIDTH constant.
##               By adding 10 to the message type the automatic line break in
##               the formated output will be omitted, e.g. for displaying
##               outputs of other commands.
## PARAMETERS:   $1: Message type:   0  = plain indent
##                                   1  = item (bullet list),
##                                   2  = info
##                                   3  = note
##                                   4  = warning
##                                   5  = error
##                                   +10= raw output (no line break, just plain
##                                        indentation)
##               $2: Message
## RETURN VAL:   0
## RETURN ECHO:  Formated message.

OvCslStrMsgFmt()
{
    typeset msg_type="$1"
    typeset rawmsg="$2"
    typeset indent_width=`echo "         " | /usr/bin/wc --chars`
    typeset output_width=`/usr/bin/expr $OVCSL_ECHO_WIDTH - \
                                $indent_width \
                                + 1`
    typeset msg_type_indent
    typeset first_line_flag=$TRUE
    typeset line_break_flag=$TRUE
    typeset opValue=""

    #Should a line break be performed?
    opValue=`/usr/bin/expr $msg_type / 10`
    if [ ${opValue} -eq 1 ]; then
        line_break_flag=$FALSE
        msg_type=`/usr/bin/expr $msg_type % 10`
    fi

    case $msg_type in
        0)
            msg_type_indent="         "
            ;;
        1)
            msg_type_indent="       * "
            ;;
        2)
            msg_type_indent="INFO:    "
            ;;
        3)
            msg_type_indent="NOTE:    "
            ;;
        4)
            msg_type_indent="WARNING: "
            ;;
        5)
            msg_type_indent="ERROR:   "
            ;;
        *)
            echo "INTERNAL ERROR: Unknown message type ID." 1>&2
            exit $OVCSL_ERROR_USAGE
            ;;
    esac

    {
        if [ $line_break_flag -eq $TRUE ]; then
            echo "$rawmsg" | /usr/bin/fmt -s -w $output_width
        else
            echo "$rawmsg"
        fi
    } | while read -r echo_line; do
            if [ $first_line_flag -eq $TRUE ]; then
                echo "${msg_type_indent}${echo_line}"
                first_line_flag=$FALSE
            else
                echo "         ""${echo_line}"
            fi
        done

    return 0
}

## FUNCTION:    OvCslStrInsertParams
## DESCRIPTION: Replaces placeholders in a source string with the contents of
##              the variables (in the manner of printf from C). A placeholder
##              starts with a @ sign and the number of the parameter to be
##              inserted here. @1 inserts $2, @2 inserts $3 and so on...
##              This function is especially useful if strings have to be stored
##              in external catalogues for L10N.
## PARAMETERS:  $1: Source string
##              $2...$x:
##                  All further parameters will replace the according place
##                  holders in the source string.
## EXAMPLE:     | src_str="Error in file @1"
##              | file="`basename $0`"
##              | OvCslStrMsgFmt 5 `OvCslStrInsertParams "$src_str" "$file"`
##              The output of this code might be something like:
##              | ERROR:   Error in file script.sh
## RETURN VAL:  0:  OK
##              1:  Less parameters specified than available in the source
##                  string
##              2:  More parameters specified than available or given
##                  parameters with no placeholder in the source string
## RETURN ECHO: String with inserted parameters.

OvCslStrInsertParams()
{
    typeset string=$1
    typeset pcount=$#
    typeset pmism_flag=$FALSE
    typeset param

    shift

    while [ $pcount -gt 1 ]; do
        pcount=`/usr/bin/expr $pcount - 1`
        eval "param=\${$pcount}"
        if echo "$string" | grep "@$pcount" > /dev/null; then
            string=`echo "$string" | sed "s/@${pcount}/${param}/g"`

        else
           pmism_flag=$TRUE
        fi
    done

    echo $string
    if echo $string | grep "@[0-9]" > /dev/null; then
        return 1
    elif [ $pmism_flag -eq $TRUE ]; then
        return 2
    fi
    return 0
}

## FUNCTION:    OvCslGetLinkTarget
## DESCRIPTION: Returns the target of a symbolic link
## PARAMETERS:  $1: Link
## RETURN VAL:  0:  Success
##              1:  $1 is not a link
## RETURN ECHO: Link target

OvCslGetLinkTarget()
{
    typeset link="$1"
    
    if [ ! -h "$link" ]
    then
        return 1
    fi
    ls -ld "$link" | sed 's/^.* -> //'
}

## FUNCTION:    OvCslGetSuperDirectory
## DESCRIPTION: Returns the directory the given file or directory is stored in.
## PARAMETERS:  $1: File system path
## RETURN VAL:  0: Success
##              1: Given path does not contain a slash.
## RETURN ECHO: Path of container directory

OvCslGetSuperDirectory()
{
    typeset path=$1
    if [ "$path" = "/" ]
    then
        echo $path
        return 0
    else
        typeset path=`echo "$path" | sed 's/\/$//'`
    fi

    typeset basename=`basename $path`

    if ! echo $path | grep -qs /; then
        return 1
    fi
    echo $path | sed "s/\/$basename$//"
    return 0
}

## FUNCTION:    OvCslGetFileProperty
## DESCRIPTION: Retrieve a specific property of a file.
## PARAMETERS:  $1: File
##              $2: Property to retrieve. You can use one of the following
##                  constants for better readability:
##                  $OVCSL_FILE_INODE (=1):
##                      Return the inode number of the file.
##                  $OVCSL_FILE_PERMISSIONS (=2):
##                      Return the permissions of the file in ls notation, e.g.
##                      "rwxrwxrwx", "rw-r--r--"
##                  $OVCSL_FILE_HARDLINKS (=3):
##                      Return the number of hardlinks to the file.
##                  $OVCSL_FILE_OWNER (=4):
##                      Return the owner of the file (see next parameter).
##                  $OVCSL_FILE_GROUP (=5):
##                      Return the group ownership of the file (see next
##                      parameter).
##                  $OVCSL_FILE_SIZE (=6):
##                      Return the file size in bytes.
##              $3: [optional]
##                  $TRUE:  Return owner and group as ID numbers
##                  $FALSE: Return owner and group as names (default)
## RETURN VAL:  0:  Success
##              1:  Unsupported property.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Specifies file not found.
## RETURN ECHO: Requested property.

# First define the property constants
OVCSL_FILE_INODE=1
OVCSL_FILE_PERMISSIONS=2
OVCSL_FILE_HARDLINKS=3
OVCSL_FILE_OWNER=4
OVCSL_FILE_GROUP=5
OVCSL_FILE_SIZE=6

OvCslGetFileProperty()
{
    typeset file=$1
    typeset property=$2
    typeset id_mode="${3:-$FALSE}"

    if [ $id_mode -eq $TRUE ]
    then
        typeset ls_opts="-lndi"
    else
        typeset ls_opts="-ldi"
    fi
    
    if [ ! -e "$file" ]
    then
        return $OVCSL_ERROR_FILE_NOT_FOUND
    fi

    typeset ls_raw="`ls $ls_opts $file`"
    typeset ls_string="`OvCslStrTrim \"$ls_raw\"`"

    case $property in
        $OVCSL_FILE_INODE)
            echo "$ls_string" | awk -F ' *' '{print $1}'
            ;;
        $OVCSL_FILE_PERMISSIONS)
            echo "$ls_string" | awk -F ' *' '{print $2}' | sed 's/^.//'
            ;;
        $OVCSL_FILE_HARDLINKS)
            echo "$ls_string" | awk -F ' *' '{print $3}'
            ;;
        $OVCSL_FILE_OWNER)
            echo "$ls_string" | awk -F ' *' '{print $4}'
            ;;
        $OVCSL_FILE_GROUP)
            echo "$ls_string" | awk -F ' *' '{print $5}'
            ;;
        $OVCSL_FILE_SIZE)
            echo "$ls_string" | awk -F ' *' '{print $6}'
            ;;
        *)
            return 1
            ;;
    esac
    
    return 0
}

## FUNCTION:    OvCslPasswdIsNisControlled
## DESCRIPTION: Checks if NIS or NIS+ controls /etc/passwd
## PARAMETERS:  - none -
## RETURN VAL:  0:  NIS or NIS+ in use
##              1:  No map for passwd available NIS or NIS+
##              2:  NIS or NIS+ not configured
## RETURN ECHO: 

OvCslPasswdIsNisControlled()
{
    if ! /usr/bin/ypwhich 1>/dev/null 2>/dev/null
    then
        return 2
    elif /usr/bin/ypcat passwd.byname 1>/dev/null 2>/dev/null
    then
        return 0
    else
        return 1
    fi
}

## FUNCTION:    OvCslGroupIsNisControlled
## DESCRIPTION: Checks if NIS or NIS+ controls /etc/group
## PARAMETERS:  - none -
## RETURN VAL:  0:  NIS or NIS+ in use
##              1:  NIS or NIS+ not in use
##              2:  NIS or NIS+ not configured
## RETURN ECHO:

OvCslGroupIsNisControlled()
{
    if ! /usr/bin/ypwhich 1>/dev/null 2>/dev/null
    then
        return 2
    elif /usr/bin/ypcat group.byname 1>/dev/null 2>/dev/null
    then
        return 0
    else
        return 1
    fi
}

## FUNCTION:    OvCslIsNisUserExisting
## DESCRIPTION: Check if the user with the given login name is already existing
##              in the NIS database.
## PARAMETERS:  $1: User login name
## RETURN VAL:  0:  User is existing in NIS database
##              1:  User not existing in NIS database
##              2:  NIS not used on system.

OvCslIsNisUserExisting()
{
    typeset user=$1;

    if OvCslPasswdIsNisControlled
    then
        if /usr/bin/ypcat passwd | cut -f 1 -d : | grep -qs "^$user$"
        then
            return 0
        else
            return 1
        fi
    else
        return 2
    fi
}

## FUNCTION:    OvCslIsNisGroupExisting
## DESCRIPTION: Check if the group with the given name is already existing in
##              the NIS database.
## PARAMETERS:  $1: Group name
## RETURN VAL:  0:  Group is existing in NIS database
##              1:  Group not existing in NIS database
##              2:  NIS not used on system.

OvCslIsNisGroupExisting()
{
    typeset group=$1

    if OvCslGroupIsNisControlled
    then
        if /usr/bin/ypcat group | cut -f 1 -d : | grep -qs "^$group$"
        then
            return 0
        else
            return 1
        fi
    else
        return 2
    fi
}

## FUNCTION:    OvCslIsLocalUserExisting
## DESCRIPTION: Check if the user with the given login name is already existing
##              in the local passwd database.
## PARAMETERS:  $1: User login name
## RETURN VAL:  0:  User is existing in local database
##              1:  User not existing in local database

OvCslIsLocalUserExisting()
{
    typeset user=$1

    if /bin/cat /etc/passwd | cut -f 1 -d : | grep -qs "^$user$"; then
        return 0
    else
        return 1
    fi
}

## FUNCTION:    OvCslIsLocalGroupExisting
## DESCRIPTION: Check if the group with the given name is already existing in
##              the local passwd database.
## PARAMETERS:  $1: Group name
## RETURN VAL:  0:  Group is existing in local database
##              1:  Group not existing in local database

OvCslIsLocalGroupExisting()
{
    typeset group="$1"

    if /bin/cat /etc/group | cut -f 1 -d : | grep -qs "^$group$"; then
        return 0
    else
        return 1
    fi
}

## FUNCTION:    OvCslIsUserExisting
## DESCRIPTION: Check if the user with the given login name is already existing
##              in the local passwd or NIS database.
##              NOTE: If you want to check if a given user is valid no matter
##                    what authentication system is in use on the system and you
##                    are sure that you can do this with root prvileges, use the
##                    function OvCslVerifyUser instead.
## PARAMETERS:  $1: User login name
## RETURN VAL:  0:  User is existing in user database
##              1:  User not existing in user database

OvCslIsUserExisting()
{
    typeset user=$1

    if OvCslIsNisUserExisting $user
    then
        return 0
    elif OvCslIsLocalUserExisting $user
    then
        return 0
    else
        return 1
    fi
}

## FUNCTION:    OvCslVerifyUser
## DESCRIPTION: Test if a user can be authenticated on a system. This function
##              differs from OvCslIsUserExisting and OvCslGetUserID:
##              - Does not look if a user is existing in /etc/passwd or NIS(+)
##                but tests if the ownership of a file can be set to the given
##                user. This is transparent to the authentification method
##                being used and works not only for /etc/passwd and 
##                NIS(+).
##              - Root privileges are needed for this function.
## PARAMETERS:  $1: User login name or user ID
## RETURN VAL:  0:  User is existing in user database
##              1:  User not existing in user database
## RETURN ECHO:

OvCslVerifyUser()
{
    typeset user=$1    
    typeset tmp_file="/tmp/ovverifyuser.$$"
    typeset opValue=""
    
    # Function called by other user than root?
    opValue=`/usr/bin/id -u`
    if [ ${opValue} -ne 0 ]
    then
        return $OVCSL_ERROR_PERMISSION_DENIED
    fi

    echo "This is a temporary test file that should get deleted in a second. If not feel free to delete it." \
         > "$tmp_file"
    if /bin/chown $user "$tmp_file" 2>/dev/null
    then
        /bin/rm -f "$tmp_file"
        return 0
    else
        /bin/rm -f "$tmp_file"
        return 1
    fi
}

## FUNCTION:    OvCslIsGroupExisting
## DESCRIPTION: Check if the group with the given name is already existing in
##              the local passwd or NIS database.
##              NOTE: If you want to check if a given group is valid no matter
##                    what authentication system is in use on the system and you
##                    are sure that you can do this with root prvileges, use the
##                    function OvCslVerifyGroup instead.
## PARAMETERS:  $1: User login name
## RETURN VAL:  0:  Group is existing in user database
##              1:  Group not existing in user database

OvCslIsGroupExisting()
{
    typeset group=$1

    if OvCslIsNisGroupExisting $group; then
        return 0;
    elif OvCslIsLocalGroupExisting $group; then
        return 0;
    else
        return 1;
    fi
}

## FUNCTION:    OvCslVerifyGroup
## DESCRIPTION: Test if a group can be authenticated on a system. This function
##              differs from OvCslIsGroupExisting and OvCslGetGroupID:
##              - Does not look if a user is existing in /etc/passwd or NIS(+)
##                but tests if the ownership of a file can be set to the given
##                group. This is transparent to the authentification method
##                being used and works not only for /etc/passwd and 
##                NIS(+).
##              - Root privileges are needed for this function.
## PARAMETERS:  $1: Group name or group ID
## RETURN VAL:  0:  Group is existing in group database
##              1:  Group not existing in group database
## RETURN ECHO:

OvCslVerifyGroup()
{
    typeset group=$1
    typeset opValue=""
    
    typeset tmp_file="/tmp/ovverifygroup.$$"
    
    # Function called by other user than root?
    opValue=`/usr/bin/id -u`
    if [ ${opValue} -ne 0 ]
    then
        return $OVCSL_ERROR_PERMISSION_DENIED
    fi

    echo "This is a temporary test file that should get deleted in a second. If not feel free to delete it." \
         > "$tmp_file"
    if /bin/chgrp $group "$tmp_file" 2>/dev/null
    then
        /bin/rm -f "$tmp_file"
        return 0
    else
        /bin/rm -f "$tmp_file"
        return 1
    fi
}

## FUNCTION:    OvCslGetUserID
## DESCRITPION: Return the user ID of a given user name either from the local
##              passwd file or from NIS(+)
## PARAMETERS:  $1: User login name
## RETURN VAL:  0:  ID successfully returned
##              1:  User name not found
## RETURN ECHO: UID of the user

OvCslGetUserID()
{

  typeset username=$1

  if OvCslIsNisUserExisting $username; then
    if /usr/bin/ypcat passwd | grep -c "^$username:" > /dev/null ; then
      /usr/bin/ypcat passwd | grep "^$username:" | cut -f 3 -d : > /dev/null
      return 0
    elif /bin/cat /etc/passwd | grep -c "^$username:" > /dev/null ; then
      /bin/cat /etc/passwd | grep "^$username:" | cut -f 3 -d : > /dev/null
      return 0
    else
      return 1
    fi
  else
    if /bin/cat /etc/passwd | grep -c "^$username:" > /dev/null ; then
      /bin/cat /etc/passwd | grep "^$username:" | cut -f 3 -d : > /dev/null
      return 0
    else
      return 1
    fi
  fi

}

## FUNCTION:    OvCslGetGroupID
## DESCRITPION: Return the group ID of a given group name either from the local
##              group file or from NIS(+)
## PARAMETERS:  $1: Group name
## RETURN VAL:  0:  ID successfully returned
##              1:  Group name not found
## RETURN ECHO: UID of the group

OvCslGetGroupID()
{

  typeset groupname=$1

  if OvCslIsNisGroupExisting $groupname; then
    if /usr/bin/ypcat group | grep -c "^$groupname:" > /dev/null ; then
      /usr/bin/ypcat group | grep "^$groupname:" | cut -f 3 -d : > /dev/null
      return 0
    elif /bin/cat /etc/group | grep -c "^$groupname:" > /dev/null ; then
      /bin/cat /etc/group | grep "^$groupname:" | cut -f 3 -d : > /dev/null
      return 0
    else
      return 1
    fi
  else
    if /bin/cat /etc/group | grep -c "^$groupname:" > /dev/null ; then
      /bin/cat /etc/group | grep "^$groupname:" | cut -f 3 -d : > /dev/null
      return 0
    else
      return 1
    fi
  fi
}

## FUNCTION:    OvCslGetUserName
## DESCRITPION: Return the user's login name of a given user id either from the
##              local passwd file or from NIS(+)
## PARAMETERS:  $1: UID
## RETURN VAL:  0:  Name successfully returned
##              1:  User id not found
## RETURN ECHO: Login name of the user

OvCslGetUserName()
{

  typeset uid=$1

  if OvCslPasswdIsNisControlled; then
    if /usr/bin/ypcat passwd | grep -c "[^:]*:[^:]*:$uid:" > /dev/null ; then
      /usr/bin/ypcat passwd | grep "[^:]*:[^:]*:$uid:" | cut -f 1 -d :
      return 0
    elif /bin/cat /etc/passwd | grep -c "[^:]*:[^:]*:$uid:" > /dev/null ; then
      /bin/cat /etc/passwd | grep "[^:]*:[^:]*:$uid:" | cut -f 1 -d :
      return 0
    else
      return 1
    fi
  else
    if /bin/cat /etc/passwd | grep -c "[^:]*:[^:]*:$uid:" > /dev/null ; then
      /bin/cat /etc/passwd | grep "[^:]*:[^:]*:$uid:" | cut -f 1 -d :
      return 0
    else
      return 1
    fi
  fi
}

## FUNCTION:    OvCslGetGroupName
## DESCRITPION: Return the group's name of a given group id either from the
##              local passwd file or from NIS(+)
## PARAMETERS:  $1: UID
## RETURN VAL:  0:  Name successfully returned
##              1:  User id not found
## RETURN ECHO: Login name of the user

OvCslGetGroupName()
{

  typeset gid=$1

  if OvCslPasswdIsNisControlled; then
    if /usr/bin/ypcat group | grep -c "[^:]*:[^:]*:$gid:" > /dev/null ; then
      /usr/bin/ypcat group | grep "[^:]*:[^:]*:$gid:" | cut -f 1 -d :
      return 0
    elif /bin/cat /etc/group | grep -c "[^:]*:[^:]*:$gid:" > /dev/null ; then
      /bin/cat /etc/group | grep "[^:]*:[^:]*:$gid:" | cut -f 1 -d :
      return 0
    else
      return 1
    fi
  else
    if /bin/cat /etc/group | grep -c "[^:]*:[^:]*:$gid:" > /dev/null ; then
      /bin/cat /etc/group | grep "[^:]*:[^:]*:$gid:" | cut -f 1 -d :
      return 0
    else
      return 1
    fi
  fi
}

## FUNCTION:    OvCslAddUser
## DESCRIPTION: Add a system user.
##              NOTE: The password field will be set to *, i.e. the created user
##              is unable to logon interactively.
## PARAMETERS:  $1: User login name
##              $2: [optional] Login shell (default: /bin/false (/bin/sh on AIX)
##                  -> do not allow interactive logon. Specify an empty string
##                  to accept the default value.
##              $3: [optional] User ID of the user (default is the highest UID
##                  in use + 1) Specify an empty string to accept the default
##                  value.
##              $4: [optional] Name of the group. Specify an empty string to
##                  accept the default value.
##              $5: [optional]
##                  $TRUE:  create home directory
##                  $FALSE: (default) Do not create home directory.
##                  NOTE: This is ignored on AIX systems
##              $6: [optional] Comment for the user.
##              $7: [optional] Homedirectory of the user. This defaults to
##                  <BASEDIR>/<LOGINNAME> on all Unices as determined by
##                  the function OvCslGetDefaultBaseHomeDir. 
## PARAMETERS:  
## RETURN VAL:  0:  User added
##              1:  Given user login name already in use.
##              2:  Gven user ID already in use.
##              3:  Specified group does not exist.
##              4:  Unable to create home directory.
##              5:  Specified home directory is not proper; need to specify absolute path.
##              6:  Specified home directory is already in use. User should specify another.
##              7:  Unable to determine default base home directory. User must specify a home directory.
##              OVCSL_ERROR_PERMISSION_DENIED:
##                  Function not called with root privileges
## RETURN ECHO: UID of the user if user was successfully added.
##

OvCslAddUser()
{
  ##############################################################
  # Function called by other user than root? 
  # Bail out immediately, no use continuing if you're not root.
  ##############################################################
  typeset opValue=""
  opValue=`/usr/bin/id -u`
  if [ ${opValue} -ne 0 ]
  then
    return $OVCSL_ERROR_PERMISSION_DENIED
  fi
    
  ###############################
  # Check user name parameter
  ###############################
  typeset user_name="$1"
  # Does the given user name already exist?
  if OvCslVerifyUser $user_name; then
    return 1
  fi
    
  ####################################################
  # Set the user's shell to /bin/false if not specified
  ####################################################
  typeset user_shell="${2:-/bin/false}"
    
  ###############################
  # Check UID parameter
  ###############################
  if [ -z "$3" ]; then
    typeset uid_opt=""
  else
    # Is the given user ID occupied?
    if OvCslGetUserName $3 > /dev/null; then
      return 2
    fi

    typeset uid_opt="-u $3"
  fi

  ###############################
  # Check group parameter
  ###############################
  typeset group="$4"
  if [ -z "$4" ]; then
    typeset group_opt=""
  else
    # Does the given group name not exist?
    if ! OvCslIsGroupExisting $group; then
      return 3
    fi

    typeset group_opt="-g $4"
  fi

  ###############################
  # Check home directory flag
  ###############################
  typeset home_flag="${5:-$FALSE}"
  if [ $home_flag -eq $TRUE ]; then
    typeset home_opt="-m"
  else
    typeset home_opt="-M"
  fi

  ###############################
  # Check comment parameter
  ###############################
  if [ -z "$6" ]
  then
    typeset comment_opt=""
  else
    typeset comment_opt="-c \"$6\""
  fi

  #############################################################################################
  # Check desired home directory parameter for whether it is absolute and not relative.
  #############################################################################################
  if [ ! -z "$7" ]
  then
    if [[ "X$7" != X/* ]]; then   # Using X as a guard here so that we get a perfect match.
      return 5
    fi
  fi

  #############################################################################################
  # Check desired home directory and create the base dir of not yet existing,
  # since useradd does not create non-existing dirs recursively.
  #############################################################################################
  if [ -z "$7" ]
  then
    # Initialize any variables we may need to use later on.
    typeset base_homedir=""
    typeset actual_homedir=""
    typeset retval=""

    base_homedir=`OvCslGetDefaultBaseHomeDir`                       # Obtaining the default base directory.
    retval=$?                                                       # Obtain the return status of the OvCslGetDefaultBaseHomeDir
    if [ $retval -eq 1 ]
    then
      return 7    # Bail out, as we are not able to determine default base home dir. User should specify home dir required.
    fi

    # Construct the home directory based on user-name.
    actual_homedir=$base_homedir"/"$1

    # Search for the pattern in the 6th field of the passwd file.
    typeset -i actual_homedir_count=`cut -d":" -f6 /etc/passwd | grep -c $actual_homedir` 

    # Now test whether the home directory (that we intend to create) is already in use.
    [[ $actual_homedir_count -gt 0 ]] && return 6
      
    # If we are here, it means that the home directory is free for use.
    # So go ahead and create its base home dir if required.
    if [ $home_flag -eq $TRUE ]; then
      if [ ! -d $base_homedir ]
      then
        if ! /bin/mkdir -p $base_homedir
        then
          return 4
        fi
        /bin/chmod 755 $base_homedir
        if [ $? -ne 0 ]
        then
          OvCslLog $loggedBy "info" "Could not change the permissions for $base_homedir.User will not be created"
        fi     
      fi
    fi

    typeset homedir_opt="-d $actual_homedir"
  else
    # Obtain the home directory that the user has specified.
    typeset desired_homedir=$7

    # Search for the pattern in the 6th field of the passwd file.
    typeset -i desired_homedir_count=`cut -d":" -f6 /etc/passwd | grep -c $desired_homedir` 

    # Now test whether the home directory that (we intend to use) is already in use by somebody else.
    [[ $desired_homedir_count -gt 0 ]] && return 6

    # If we are here, it means that the home directory is free for use.
    # So go ahead and create the base home dir if required.
    if [ $home_flag -eq $TRUE ]; then
      typeset basedir=`OvCslGetSuperDirectory $7`
      if [ ! -d $basedir ]
      then
        if ! /bin/mkdir -p $basedir
        then
          return 4
        fi
        /bin/chmod 755 $basedir
         if [ $? -ne 0 ]
	 then
	      OvCslLog $loggedBy "info" "Could not change the permissions for $basedir.User will not be created"
        fi  
      fi
    fi

    typeset homedir_opt="-d $7"
  fi
     
  ###############################
  # Add the user
  ###############################
  if eval /usr/sbin/useradd $uid_opt \
                    $group_opt \
                    $home_opt \
                    $comment_opt \
                    -s $user_shell \
                    $homedir_opt \
                    $user_name 1>/dev/null 2>/dev/null; then
    OvCslGetUserID $user_name
    return 0
  else
    return $OVCSL_ERROR_UNKNOWN
  fi
}

## FUNCTION:    OvCslAddGroup
## DESCRIPTION: Add a system group.
## PARAMETERS:  $1: Group name
##              $2: [optional] Group ID of the group (default value see next
##                  parameter. NOTE: This parameter is ignored on AIX
##              $3: [optional] Group is a system group. This option may not be
##                  used in combination with $2.
##                  $TRUE: Create a system group (GID below the ID limit for
##                         groups and above the highest occupied ID + 1)
##                  $FALSE (default) GID is the highest GID above the ID for 
##                         the user groups in use + 1)
##                  NOTE: This parameter is only working on Linux and AIX.
## RETURN VAL:  0:  Group added
##              1:  Given group name already in use.
##              2:  Given group ID already in use.
##              OVCSL_ERROR_PERMISSION_DENIED:
##                  Function not called with root privileges
## RETURN ECHO: GID of the group if group was successfully added or if the user is
##              already existing in the database.

OvCslAddGroup()
{
    # Function called by other user than root?
    if [ `/usr/bin/id -u` -ne 0 ]; then
        return $OVCSL_ERROR_PERMISSION_DENIED
    fi

    if ! OvCslVerifyGroup $1; then
        typeset group_name=$1
    else
        return 1
    fi
    
    if [ -z "$2" ]; then
        typeset group_id_opt=""
    else
        if OvCslGetGroupName $2 > /dev/null; then
            return 2
        fi
        typeset group_id_opt="-g $2"
    fi  
  
    typeset admin_flag="${3:-$FALSE}"
    if [ $admin_flag -eq $TRUE ]; then
        typeset admin_opt="-r"
    else
        typeset admin_opt=""
    fi
    
    if /usr/sbin/groupadd $admin_opt $group_id_opt $group_name
    then
        OvCslGetGroupID $group_name
        return 0
    else
        return $OVCSL_ERROR_UNKNOWN
    fi
    
}

## FUNCTION:    OvCslDeleteUser
## DESCRIPTION: Delete a user from the local /etc/passwd database.
## PARAMETERS:  $1: User login name
##              $2: [optional] Delete the users home directory?
##                  $TRUE:  Yes, do it.
##                  $FALSE: No, leave the home directory untouched (default).
##                  NOTE: This is ignored on AIX
## RETURN VAL:  0: User deleted
##              1: User does not exist in /etc/passwd.
##              OVCSL_ERROR_PERMISSION_DENIED:
##                  Function not called with root privileges

OvCslDeleteUser()
{
    typeset opValue=""
    # Function called by other user than root?
    opValue=`/usr/bin/id -u`
    if [ ${opValue} -ne 0 ]; then
        return $OVCSL_ERROR_PERMISSION_DENIED
    fi

    typeset user_name=$1
    
    # Check if user exists in /etc/passwd (not in NIS(+))
    if ! OvCslIsLocalUserExisting $user_name; then
        return 1
    fi
    typeset home_flag="${2:-$FALSE}"
    if [ $home_flag -eq $TRUE ]; then
        typeset home_opt="-r"
    else
        typeset home_opt=""
    fi  
    
    if /usr/sbin/userdel $home_opt $user_name; then
        return 0
    else
        return $OVCSL_ERROR_UNKNOWN
    fi
}

## FUNCTION:    OvCslDeleteGroup
## DESCRIPTION: Delete a group from the local /etc/group database.
## PARAMETERS:  $1: Group name
## RETURN VAL:  0: Group deleted
##              1: Group does not exist in /etc/group.
##              OVCSL_ERROR_PERMISSION_DENIED:
##                  Function not called with root privileges

OvCslDeleteGroup()
{
    typeset opValue=""
    # Function called by other user than root?
    opValue=`/usr/bin/id -u`
    if [ ${opValue} -ne 0 ]; then
        return $OVCSL_ERROR_PERMISSION_DENIED
    fi
    
    typeset group_name=$1

    # Check if group exists in /etc/group (not in NIS(+))
    if ! OvCslIsLocalGroupExisting $group_name
    then
        return 1
    fi
    
    if /usr/sbin/groupdel $group_name; then
        return 0
    else
        return $OVCSL_ERROR_UNKNOWN
    fi
}

## FUNCTION:    OvCslGetDefaultBaseHomeDir
## DESCRIPTION: Determines OS specific default base home directory.
## PARAMETERS:  - none -
## RETURN VAL:  0: Base home directory found.
##              1: Unable to determine base home directory. Assuming default.
##              OVCSL_ERROR_PERMISSION_DENIED:
##                  Function not called with root privileges
## RETURN ECHO: Value of default base home directory.

OvCslGetDefaultBaseHomeDir()
{
  typeset opValue=""
  # Function called by other user than root?
  opValue=`/usr/bin/id -u`
  if [ ${opValue} -ne 0 ]; then
    return $OVCSL_ERROR_PERMISSION_DENIED
  fi
   
  typeset base_homedir="/home"

  base_homedir=`/usr/sbin/useradd -D | awk -F "=" '/HOME/ {print $2;}'`
    
  # Output the value of the default base home directory.
  echo $base_homedir

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

## FUNCTION:    OvCslGetFstabMountPoints
## DESCRIPTION: Returns a list of mount points defined in the /etc/fstab
##              file.
## PARAMETERS:  - none -
## RETURN VAL:  0:  Success
##              $OVCSL_ERROR_READING_FILE:
##                  Unable to read /etc/fstab.
## RETURN ECHO: List of lokal mount points

OvCslGetFstabMountPoints()
{
    [ -r "/etc/fstab" ] || return $OVCSL_ERROR_READING_FILE

    /bin/cat /etc/fstab | sed "s/^#.*$//" \
                  | OvCslFilterEmptyLines \
                  | awk '{ print $2 }'
}

## FUNCTION:    OvCslGetMountedMountPoints
## DESCRIPTION: Returns a list of currently mounted mount points.
## PARAMETERS:  - none -
## RETURN VAL:  0:  Success
## RETURN ECHO: List of mounted mount points

OvCslGetMountedMountPoints()
{
    /bin/mount | awk '{print $3}'
}

#
# AutoFS functions
#

#  FUNCTION:    _OvCslPreprocessAutoMaster
#  DESCRIPTION: Searches the a automount master configuration file for commands
#               to include external datasources and expands these sources by
#               their contents. This function is mainly intended as helper
#               function and is not for external use.
#               Currently this function supports files and NIS(+) maps as
#               external sources.
#  PARAMETERS:  $1: Name of the file to preprocess
#               $2: Call index. Specify 0 here
#  RETURN VAL:  0: Success
#               1: At least one datasource could not be read.
#  RETURN ECHO: Preprocessed automount master configuration file.

_OvCslPreprocessAutoMaster()
{
    typeset src_file=$1
    typeset call_index=`/usr/bin/expr $2 + 1 `
    typeset config_line=""
    typeset nis_dump=/tmp/ov_automasternisdump_${call_index}_$$
    typeset read_failed=$FALSE

    cat "$src_file" | while read config_line
    do
        # Include a file...
        if echo $config_line | grep -qs "^+/"
        then
            typeset inc_file="`echo -e $config_line | sed s/^+//`"
            if [ -r "$inc_file" ]
            then
                _OvCslPreprocessAutoMaster "$inc_file" ${call_index}
            else
                read_failed=$TRUE
            fi
        # Or include a NIS map here...
        elif echo $config_line | grep -qs "^+"
        then
            # Hm, this could be a NIS map, let's check this.
	   if [ -r /etc/nsswitch.conf ]
	       then
                  if  /bin/cat /etc/nsswitch.conf | grep '^automount:' | grep -qs nis
                  then
                    typeset nis_map="`echo -e $config_line | sed s/^+//`"
                    if /usr/bin/ypcat `basename $nis_map` > $nis_dump 2>/dev/null
                    then
                        _OvCslPreprocessAutoMaster "$nis_dump" ${call_index}
                    else
                        read_failed=$TRUE
                    fi
	          fi	
            fi
         else
            echo $config_line
         fi
    done

    /bin/rm -f $nis_dump

    if [ $read_failed -eq $TRUE ]
    then
        return 1
    else
        return 0
    fi
}

## FUNCTION:    OvCslDumpAutomountDatabase
## DESCRIPTION: Dump the automount configuration database as configured in
##              /etc/nsswitch.conf. The dumped file will combine the data from
##              the supported sources in the order they are configured.
##              Currently supported sources: file, nis, nisplus
## PARAMETERS:  $1: Path to the output file.
## RETURN VAL:  0:  Success
##              1:  Unable to read at least one data source. This must not be
##                  a critical error.
##              2:  Unsupported data source found.
##              $OVCSL_ERROR_READING_FILE:
##                  Unable to read nsswitch.conf
##              $OVCSL_ERROR_WRITING_FILE:
##                  Unable to write output file.
## RETURN ECHO: - None -

OvCslDumpAutomountDatabase()
{
    typeset outfile="$1"

    if ! touch "$outfile"
    then
        return $OVCSL_ERROR_WRITING_FILE
    fi
    
    # Delete the contents of the output file
    > "$outfile"

    # Is the automounter configuration controlled by nsswitch.conf?
    if [ -r "/etc/nsswitch.conf" ]
    then
    if ! /bin/cat /etc/nsswitch.conf | grep -qs '^automount:'
    then
        /bin/cat /etc/auto.master >> "$outfile"
    else
        typeset nsswitch_line=`/bin/cat /etc/nsswitch.conf | grep '^automount:'`
        
        typeset field="foo" # Something stupid to enter the while loop
        typeset field_no="2"
        typeset status=""

        while [ -n "$field" ]
        do
            field=`echo "$nsswitch_line" | awk "{print \\$\$field_no}"`
                if [ -n "$field" ]
                then
                case "$field" in
                    "files")
                        if [ -r "/etc/auto.master" ]
                        then
                            /bin/cat /etc/auto.master >> "$outfile"
                            status="success"
                        else
                            status="unavail"
                        fi
                        ;;
                    "nis" | "nisplus")
                        if /usr/bin/ypcat `basename /etc/auto.master` > /dev/null 2>/dev/null
                        then
                            /usr/bin/ypcat `basename /etc/auto.master` >> "$outfile"
                            status="success"
                        else
                            status="unavail"
                        fi

                        ;;
                    *)
                        # Is the field a status and action directive?
                        if echo $field | grep -qs "^\[.*\]$"
                        then
                            if echo $field | grep -qis "unavail=return" \
                               || echo $field | grep -qis "tryagain=return"
                            then
                                if [ $status == "unavail" ]
                                then
                                    # Do not continue processing other fields
                                    $field=""
                                fi
                            elif echo $field | grep -qis "notfound=return"
                            then
                                # Do not continue processing other fields
                                $field=""
                            fi
                        else                    
                            return 1
                        fi
                        ;;
                esac
            fi
            field_no=`/usr/bin/expr $field_no + 1`
        done
    fi
    fi   
    # Finally include all the external sources mentioned in the configuration
    
    _OvCslPreprocessAutoMaster ${outfile} 0 > ${outfile}.preproc
    /bin/mv ${outfile}.preproc ${outfile}
        
    return 0
}

## FUNCTION:    OvCslAfsGetMapRootDirs
## DESCRIPTION: Returns root directories of mount maps for AutoFS.
##              NOTE: Depending on the configuration this function may take a
##              while to finish. If you need to reuse the obtained information
##              you should consider dumping the output to a file and read this
##              file for subsequent queries.
## PARAMETERS:  -None-
## RETURN VAL:  0: Success
##              1:  Unable to dump automount master configuration file. See the
##                  desription of the function OvCslDumpAutomountDatabase for
##                  more information.
## RETURN ECHO: List of map root directories.

OvCslAfsGetMapRootDirs()
{
    # Do not use the OV tmp directory here, since this function may be called
    # to test, if this may be created or not.
    typeset dumped_auto_master=/tmp/ov_auto_master.$$
    
    OvCslDumpAutomountDatabase "$dumped_auto_master"
    if [ $? -eq 2 ]
    then
        return 1
    fi
    
    typeset config_line=""
    /bin/cat $dumped_auto_master | while read config_line
    do
        if echo $config_line | grep -qs "^/"
        then
            # Do not echo direct mount maps
            if ! echo $config_line \
                 | awk '{print $2}' \
                 | grep -v -- "-hosts" \
                 | grep -v -- "-null" \
                 | grep -qs "^-"
            then
                echo $config_line | awk '{print $1}'
            fi
        fi
    done
    
    /bin/rm -f $dumped_auto_master
}

## FUNCTION:    OvCslAfsGetDirectMountPoints
## DESCRIPTION: Returns a list of direct mount points.
##              NOTE: Depending on the configuration this function may take a
##              while to finish. If you need to reuse the obtained information
##              you should consider dumping the output to a file and read this
##              file for subsequent queries.
## PARAMETERS:  -None-
## RETURN VAL:  0: Success
##              1: Unable to obtain configuration
## RETURN ECHO: List of map root directories.

OvCslAfsGetDirectMountPoints()
{
    # Do not use the OV tmp directory here, since this function may be called
    # to test, if this may be created or not.
    typeset dumped_auto_master=/tmp/ov_auto_master.$$

    OvCslDumpAutomountDatabase "$dumped_auto_master"
    if [ $? -eq 2 ]
    then
        return 1
    fi

    typeset config_line=""
    /bin/cat $dumped_auto_master | while read config_line
    do
        if echo $config_line | grep -qs "^/"
        then
            # Only echo direct mount maps and filter special maps
            if echo $config_line \
                 | awk '{print $2}' \
                 | grep "^-" \
                 | grep -v -- "-hosts" \
                 | grep -vqs -- "-null"
            then
                echo $config_line | awk '{print $1}'
            fi
        fi
    done

    /bin/rm -f $dumped_auto_master
}

## FUNCTION:    OvCslAfsGetMapMountPoints
## DESCRIPTION: Returns a list of mount points specified by the given map name.
##              The mount points will be given as absolute path names.
##              NOTE: Depending on the configuration this function may take a
##              while to finish. If you need to reuse the obtained information
##              you should consider dumping the output to a file and read this
##              file for subsequent queries.
## PARAMETERS:  $1: Name of map root directory
## RETURN VAL:  0: Success
##              1: Unable to obtain configuration
##              2: Cannot read local map.
##              3: Cannot read NIS map.
##              4: Cannot launch program to obtain map.
##              5: Unsupported map type.
## RETURN ECHO: List of map root directories.

OvCslAfsGetMapMountPoints()
{
    typeset map_root_dir="`echo $1 | sed 's/\/$//'`"
    typeset dumped_master=/tmp/ov_auto_master.$$
    typeset dumped_map=/tmp/ov_auto_map.$$

    OvCslDumpAutomountDatabase "$dumped_master"
    if [ $? -eq 2 ]
    then
        return 1
    fi

    typeset wspaces=`echo -e " \t\v"`
    typeset map=`/bin/cat $dumped_master | grep "^$map_root_dir[$wspaces]" \
                                           | awk '{ print $2 }'`
    # What kind of map do we have to deal with here?...
    # ... a NIS(+) map,...
    if echo "$map" | grep -qs "^yp:" \
         || echo "$map" | grep -qs "^nisplus:"
    then
        map=`echo "$map" | sed 's/^yp://' | sed 's/^nisplus://'`
        if ! /usr/bin/ypcat "$map" > $dumped_map 2>/dev/null
        then
            /bin/rm -f $dumped_map
            /bin/rm -f $dumped_master
            return 3
        fi
    # ...dynamical generated via a program,...
    elif echo "$map" | grep -qs "^program:"
    then
        map="`echo "$map" | sed 's/^program://'`"
        if ! $map > $dumped_map 2>/dev/null
        then
            /bin/rm -f $dumped_master
            /bin/rm -f $dumped_map
            return 4
        fi
    # ...A local file,...
    elif echo "$map" | grep -v ":" \
                     | grep -vqs -- "^-"
    then
        # Is the file given as relative path name? Then convert to absolute.
        if echo "$map" | grep -vqs "^/"
        then
            map="/etc/$map"
        fi
        if ! /bin/cat "$map" > $dumped_map 2>/dev/null
        then
            /bin/rm -f $dumped_map
            /bin/rm -f $dumped_master
            return 2
        fi
    # Ignore -hosts and -null maps
    elif ( echo "$map" | grep -qs -- "-hosts" ) \
         || ( echo "$map" | grep -qs -- "-null" )
    then
        /bin/rm -f $dumped_map
        /bin/rm -f $dumped_master
	return 0
    # ...or an unsupported map?
    else
        /bin/rm -f $dumped_master
        return 5
    fi

    # Print the absolute path names of the mount point to STDOUT
    typeset map_line=""
    typeset rel_mount_point=""
    /bin/cat $dumped_map | sed 's/#.*$//' \
                      | OvCslFilterEmptyLines \
                      | while read map_line
    do
        rel_mount_point=`echo $map_line | awk '{ print $1 }'`
        echo "${map_root_dir}/${rel_mount_point}"
    done

    /bin/rm -f $dumped_master
    /bin/rm -f $dumped_map
}

## FUNCTION:    OvCslAfsGetMountPoints
## DESCRIPTION: Returns a list of all mount points that can be found on the
##              system.
##              NOTE: Depending on the configuration this function may take a
##              while to finish. If you need to reuse the obtained information
##              you should consider dumping the output to a file and read this
##              file for subsequent queries.
## PARAMETERS:  - None -
## RETURN VAL:  0:  Success
##              1:  Unable to obtain configuration. Generation of list cannot be
##                  completed. This is a fatal error. Possible missconfiguration
##                  Auto FS.
##              2:  At least one map was unsupported. However all other maps
##                  were read. Possibly some unsupported map types are
##                  configured.
## RETURN ECHO: List of mount points.

OvCslAfsGetMountPoints()
{

    # First print direct mount points
    if ! OvCslAfsGetDirectMountPoints
    then
        return 1
    fi

    # Now list all indirect mount points
    typeset root_dir=""
    typeset tmp_ret_val=0
    typeset ret_val=0
    for root_dir in `OvCslAfsGetMapRootDirs`
    do
        OvCslAfsGetMapMountPoints $root_dir
        tmp_ret_val=$?
        if [ $tmp_ret_val -eq 1 ]
        then
            return 1
        elif [ $tmp_ret_val -gt 1 ]
        then
            ret_val=`/usr/bin/expr $ret_val + $tmp_ret_val`
        fi
    done

    if [ $ret_val -gt 0 ]
    then
        return 2
    else
        return 0
    fi
}

## FUNCTION:    OvCslAfsIsConfigured.
## DESCRIPTION: Checks, if AutoFS is configured on the system.
## PARAMETERS:  - None -
## RETURN VAL:  0: Success
## RETURN ECHO: $TRUE:  AutoFS is configured
##              $FALSE: AutoFS is not configured

OvCslAfsIsConfigured()
{
    if [ -r /etc/auto.master ]
    then
        echo $TRUE
    else
        echo $FALSE
    fi
}

## FUNCTION:    OvCslAfsIsRunning.
## DESCRIPTION: Checks, if AutoFS is running on the system.
## PARAMETERS:  - None -
## RETURN VAL:  0: Success
## RETURN ECHO: $TRUE:  AutoFS is running
##              $FALSE: AutoFS is not running

OvCslAfsIsRunning()
{

    if ps -ef | grep -v grep | grep -qs automount
    then
        echo $TRUE
    else
        echo $FALSE
    fi
}

## FUNCTION:    OvCslCheckMountPoint
## DESCRIPTION: Checks if a directory is a moint point either through auto
##              mounter or through /etc/fstab.
## PARAMETERS:  $1: Directory to check
## RETURN VAL:  0:  Check completed successfully
##              1:  Directory is a mount point, but it's not possible to change
##                  the current working directory to this directory. The moint
##                  point is possibly missconfigured or it is mounted on a
##                  remote file system that does not respond.
##              2:  Given directory does exist, but is not a directory.
##              3:  Unable to complete the check. There may be a missconfigured
##                  automounter or a
## RETURN ECHO: Compare against the available constants described below to check
##              the state.
##              $OVCSL_MOUNTPOINT_PLAIN_DIR:
##                  Directory is existing and not configured as mount point.
##              $OVCSL_MOUNTPOINT_NOT_EXISTING:
##                  Directory is not existing, but is also not configured as
##                  mount point.
##              $OVCSL_MOUNTPOINT_MISCONFIGURED:
##                  Directory is not existing, but is configured as mount
##                  point -> Obviously missconfigured file system.
##              $OVCSL_MOUNTPOINT_NOT_MOUNTED:
##                  Directory is existing and is configured as mount point, but
##                  currently not mounted.
##              $OVCSL_MOUNTPOINT_MOUNTED:
##                  Directory is existing and is configured as mount point and
##                  mounted.
##              $OVCSL_MOUNTPOINT_AUTOMOUNTED:
##                  Directory is configured as auto mount point
##              $OVCSL_MOUNTPOINT_AUTOMOUNT_MAP_ROOT
##                  Directory is the root directory of an automount map
##              $OVCSL_MOUNTPOINT_AUTOMOUNTED_NOT_RUNNING:
##                  Same as above, but the automounter is currently not running.
##              $OVCSL_MOUNTPOINT_AUTOMOUNT_MAP_ROOT_NOT_RUNNING
##                  Same as above, but the automounter is currently not running.
##              $OVCSL_MOUNTPOINT_AUTOMOUNTED_NOT_EXISTING:
##                  Directory is located below an automount map root but is
##                  not existing in the map.

OVCSL_MOUNTPOINT_PLAIN_DIR=0
OVCSL_MOUNTPOINT_NOT_EXISTING=1
OVCSL_MOUNTPOINT_MISCONFIGURED=2
OVCSL_MOUNTPOINT_NOT_MOUNTED=3
OVCSL_MOUNTPOINT_MOUNTED=4
OVCSL_MOUNTPOINT_AUTOMOUNTED=5
OVCSL_MOUNTPOINT_AUTOMOUNT_MAP_ROOT=6
OVCSL_MOUNTPOINT_AUTOMOUNTED_NOT_RUNNING=7
OVCSL_MOUNTPOINT_AUTOMOUNT_MAP_ROOT_NOT_RUNNING=8
OVCSL_MOUNTPOINT_AUTOMOUNTED_NOT_EXISTING=9

OvCslCheckMountPoint()
{
    typeset dir=$1
    typeset afs_mount_points=/tmp/ov_afs_mount_points.$$
    typeset afs_map_root_dirs=/tmp/ov_afs_map_root_dirs.$$
    typeset opValue=""
    typeset superDir=""

    # If the dir is a link, resolve the link.
    if [ -h "$dir" ]
    then
        dir=`OvCslGetLinkTarget "$dir"`
    fi

    # Is the given dir really a dir?
    if [ -r "$dir" ] && [ ! -d "$dir" ]
    then
        return 1
    fi

    # Check for automounter
    opValue=`OvCslAfsIsConfigured`
    if [ ${opValue} -eq $TRUE ]
    then
        if ! OvCslAfsGetMountPoints > $afs_mount_points
        then
            /bin/rm -f $afs_mount_points
            return 3
        fi
        if ! OvCslAfsGetMapRootDirs > $afs_map_root_dirs
        then
            /bin/rm -f $afs_mount_points
            /bin/rm -f $afs_map_root_dirs
            return 3
        fi

        superDir=`OvCslGetSuperDirectory $dir`
        if /bin/cat $afs_mount_points | grep -qs "^${dir}$"
        then
            /bin/rm -f $afs_mount_points
            /bin/rm -f $afs_map_root_dirs
            opValue=`OvCslAfsIsRunning`
            if [ ${opValue} -eq $TRUE ]
            then
                echo $OVCSL_MOUNTPOINT_AUTOMOUNTED
                if ( cd $dir 2>/dev/null )
                then
                    return 0
                else
                    return 1
                fi
            else
                echo $OVCSL_MOUNTPOINT_AUTOMOUNTED_NOT_RUNNING
                return 0
            fi
        elif /bin/cat $afs_map_root_dirs | grep -qs "^${dir}$"
        then
            /bin/rm -f $afs_mount_points
            /bin/rm -f $afs_map_root_dirs
            opValue=`OvCslAfsIsRunning`
            if [ ${opValue} -eq $TRUE ]
            then
                echo $OVCSL_MOUNTPOINT_AUTOMOUNT_MAP_ROOT
                if ( cd $dir 2>/dev/null )
                then
                    return 0
                else
                    return 1
                fi
            else
                echo $OVCSL_MOUNTPOINT_AUTOMOUNT_MAP_ROOT_NOT_RUNNING
                return 0
            fi
        elif /bin/cat $afs_map_root_dirs | grep -qs "^${superDir}$"
        then
            /bin/rm -f $afs_mount_points
            /bin/rm -f $afs_map_root_dirs
            echo $OVCSL_MOUNTPOINT_AUTOMOUNTED_NOT_EXISTING
            return 0
        fi
    fi
    /bin/rm -f $afs_mount_points
    /bin/rm -f $afs_map_root_dirs

    # Check for lokal mount points
    typeset mount_points=/tmp/ov_mount_points.$$
    typeset mounted_points=/tmp/ov_mounted_points.$$

    OvCslGetFstabMountPoints > $mount_points
    OvCslGetMountedMountPoints > $mounted_points

    if /bin/cat $mount_points | grep -qs "^${dir}$"
    then
        if [ ! -d "$dir" ]
        then
            echo $OVCSL_MOUNTPOINT_MISCONFIGURED
        elif /bin/cat $mounted_points | grep -qs "^${dir}$"
        then
            echo $OVCSL_MOUNTPOINT_MOUNTED
            /bin/rm -f $mount_points
            /bin/rm -f $mounted_points
            if ( cd $dir 2>/dev/null )
            then
                return 0
            else
                return 1
            fi
        else
            echo $OVCSL_MOUNTPOINT_NOT_MOUNTED
        fi
        /bin/rm -f $mount_points
        /bin/rm -f $mounted_points
        return 0
    fi
    /bin/rm -f $mount_points
    /bin/rm -f $mounted_points

    # Directory is obviously not mounted
    if [ -d "$dir" ]
    then
        echo $OVCSL_MOUNTPOINT_PLAIN_DIR
    else
        echo $OVCSL_MOUNTPOINT_NOT_EXISTING
    fi

    return 0
}

## FUNCTION:    OvCslRotateLog
## DESCRIPTION: Rotate a log file: Check if the log file exceeds a given size.
##              If so, make a compressed backup of the log file and create a
##              new empty file. 3 backups will be stored. The oldest existing
##              backup will be deleted.
## PARAMETERS:  $1: Path of the log file
##              $2: Maximum size in KB
## RETURN VAL:  0
##              $OVCSL_ERROR_DELETING_FILE
##              $OVCSL_ERROR_MOVING_FILE
## RETURN ECHO:

OvCslRotateLog()
{
    if [ -f "$1" ]
    then
        typeset log_size=`du -k "$1" | cut -f 1`
        if [ $log_size -gt $2 ]
        then
            typeset log_name="`basename $1`"
            typeset log_dir="`echo $1 | sed s/\\/$log_name$//`"
            if [ -f "${1}.3.Z" ]
            then
                if ! /bin/rm -f "${1}.3.Z"
                then
                    return $OVCSL_ERROR_DELETING_FILE
                fi
            fi
            if [ -f "${1}.2.Z" ]
            then
                if ! /bin/mv "${1}.2.Z" "${1}.3.Z"
                then
                    return $OVCSL_ERROR_MOVING_FILE
                fi
            fi
            if [ -f "${1}.1.Z" ]
            then
                if ! /bin/mv "${1}.1.Z" "${1}.2.Z"
                then
                    return $OVCSL_ERROR_MOVING_FILE
                fi
            fi
            if /bin/mv "${1}" "${1}.1"
            then
                if [ -x /usr/bin/compress  ]
                then
                    /usr/bin/compress  "${1}.1"
                fi
                touch "${1}"
            else
                return $OVCSL_ERROR_MOVING_FILE
            fi
        fi
    fi
}

## FUNCTION:    OvCslAddLineToFile
## DESCRIPTION: Add a line to a file, either at the end, after the first line
##              that matches a regular expression A, before the first line that
##              matches a regular expression B or between two lines that match
##              regular expressions A and B.
##              A line will be added only at the first match. Further matches
##              will be ignored.
##              For removing a line from a file see OvCslRemoveLineFromFile.
## PARAMETERS:  $1: File to which the line should be added.
##              $2: The line to be added to the file specified by $1.
##              $3: [optional] regular expression (grep) of a line (A), after
##                  which the line should be added. "" to ignore the preceeding
##                  line and only care about the following line ($4).
##              $4: [optional] regular expression (grep) of a line (B), after
##                  which the line should be added.
## RETURN VAL:  O:  OK
##              1:  Regular expression in $3 and/or $4 not found.
##              2:  Unable to create temporary file
##              $OVCSL_ERROR_WRITING_FILE, $OVCSL_ERROR_INVALID_PATH,
##              $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO:

OvCslAddLineToFile()
{
    [ -e "$1" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$1" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }
    [ -w "$1" ] || { return $OVCSL_ERROR_WRITING_FILE; }

    typeset src_file="$1"
    typeset add_line="$2"
    typeset re_prev="${3:-.*}"
    typeset re_next="${4:-.*}"

    typeset prev_line=""
    typeset cur_line=""
    typeset matched_flag=$FALSE
    typeset eof_flag=$FALSE

    typeset tmp_file=`OvCslGetOvTemp`/tmp-result-$$
    if ! touch $tmp_file
    then
        return 2
    fi

    # If no regular expressions are specified, append the given line to the file
    if [ $# -eq 2 ]
    then
        if ! echo $add_line >> $src_file
        then
            return $OVCSL_ERROR_WRITING_FILE
        else
            return 0
        fi
    fi
    typeset mstate_file=`OvCslGetOvTemp`/tmp-state-$$
    echo $matched_flag > $mstate_file

    # OK, the user want the complicated way

    /bin/cat "$src_file" | while
        if ! read cur_line
        then
            cur_line=""
            eof_flag=$TRUE
        fi

        if [ $matched_flag  -eq $FALSE ]
        then
            if echo "$prev_line" | grep "$re_prev" > /dev/null && echo "$cur_line" | grep "$re_next" > /dev/null
            then
                echo "$add_line" >> $tmp_file
                if [ $eof_flag -eq $FALSE ]
                then
                    echo "$cur_line" >> $tmp_file
                fi
                matched_flag=$TRUE
                echo $matched_flag > $mstate_file
            else
                if [ $eof_flag -eq $FALSE ]
                then
                    echo "$cur_line" >> $tmp_file
                fi
            fi
        else
            if [ $eof_flag -eq $FALSE ]
            then
                echo "$cur_line" >> $tmp_file
            fi
        fi

        if [ $eof_flag -eq $FALSE ]
        then
            /bin/true
        else
            /bin/false
        fi
    do
        prev_line=$cur_line
    done
    matched_flag=`/bin/cat $mstate_file`
    /bin/rm -f $mstate_file
    if ! /bin/mv $tmp_file $src_file
    then
        return $OVCSL_ERROR_WRITING_FILE
    else
        if [ $matched_flag -eq $TRUE ]
        then
            return 0
        else
            return 1
        fi
    fi
}

## FUNCTION:    OvCslRemoveLineFromFile
## DESCRIPTION: Remove a line that matches a regular expression A from a file,
##              that either matches an expression A, after the first line that
##              matches a regular expression B, before the first line that
##              matches a regular expression C, between two lines that match
##              regular expressions B and C or any combination of these
##              expressions.
##              For adding a line to a file see OvCslAddLineToFile.
## PARAMETERS:  $1: File from which the line shall be removed.
##              $2: Regular expression (grep) of a line (A) that should be
##                  removed.
##              $3: [optional] regular expression (grep) of a line (B), after
##                  which the line should be removed. "" to ignore the
##                  preceeding line and only care about the following line ($4).
##              $4: [optional] regular expression (grep) of a line (C), before
##                  which the line should be removed.
## RETURN VAL:  O:  OK
##              1:  Regular expression in $2, $3 and/or $4 not found.
##              2:  Unable to create temporary file
##              $OVCSL_ERROR_WRITING_FILE, $OVCSL_ERROR_INVALID_PATH,
##              $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO:

OvCslRemoveLineFromFile()
{
    [ -e "$1" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$1" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }
    [ -w "$1" ] || { return $OVCSL_ERROR_WRITING_FILE; }

    typeset src_file="$1"
    typeset re_remove="$2"
    typeset re_prev="${3:-.*}"
    typeset re_next="${4:-.*}"

    typeset prev_line=""
    typeset cur_line=""
    typeset next_line=""
    typeset matched_flag=$FALSE
    typeset bof_flag=$FALSE
    typeset eof_flag=$FALSE

    typeset tmp_file=`OvCslGetOvTemp`/tmp-result-$$

    if ! touch $tmp_file
    then
        return 2
    fi
    typeset mstate_file=`OvCslGetOvTemp`/tmp-state-$$
    echo $matched_flag > $mstate_file

    /bin/cat "$src_file" | while
        if ! read next_line
        then
            next_line=""
            eof_flag=$TRUE
        fi
        if [ $bof_flag -eq $TRUE ]
        then
            if [ $matched_flag -eq $FALSE ]
            then
                if echo "$prev_line" | grep "$re_prev" > /dev/null && \
                   echo "$cur_line" | grep "$re_remove" > /dev/null && \
                   echo "$next_line" | grep "$re_next" > /dev/null
                then
                    matched_flag=$TRUE
                    echo $matched_flag > $mstate_file
                else
                   echo "$cur_line" >> $tmp_file
                fi
            else
                echo "$cur_line" >> $tmp_file
            fi
        fi

        if [ $eof_flag -eq $FALSE ]
        then
            /bin/true
        else
            /bin/false
        fi
    do
        prev_line=$cur_line
        cur_line=$next_line
        bof_flag=$TRUE
    done
    matched_flag=`/bin/cat $mstate_file`
    /bin/rm -f $mstate_file
    if ! /bin/mv $tmp_file $src_file
    then
        return $OVCSL_ERROR_WRITING_FILE
    else
        if [ $matched_flag -eq $TRUE ]
        then
            return 0
        else
            return 1
        fi
    fi
}

## FUNCTION:    OvCslGetLineFromFile
## DESCRIPTION: Search for a line that matches a regular expression A from a
##              file that either matches a regular expression A, after the first
##              line that matches a regular expression B, before the first line
##              that matches a regular expression C, between two lines that
##              match regular expressions B and C or any combination of these
##              expressions.
## PARAMETERS:  $1: File to get the line from.
##              $2: Regular expression (grep) of a line (A) that should be
##                  removed.
##              $3: [optional] regular expression (grep) of a line (B), after
##                  which the line should be removed. "" to ignore the
##                  preceeding line and only care about the following line ($4).
##              $4: [optional] regular expression (grep) of a line (C), before
##                  which the line should be removed.
## RETURN VAL:  O:  OK
##              1:  Regular expression in $2, $3 and/or $4 not found.
##              $OVCSL_ERROR_INVALID_PATH, $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO: Matched line.

OvCslGetLineFromFile()
{
    [ -e "$1" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$1" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }

    typeset src_file="$1"
    typeset re_remove="$2"
    typeset re_prev="${3:-.*}"
    typeset re_next="${4:-.*}"

    typeset prev_line=""
    typeset cur_line=""
    typeset next_line=""
    typeset matched_flag=$FALSE
    typeset bof_flag=$FALSE
    typeset eof_flag=$FALSE

    typeset tmp_file=`OvCslGetOvTemp`/tmp-result-$$
    typeset mstate_file=`OvCslGetOvTemp`/tmp-state-$$
    echo $matched_flag > $mstate_file

    /bin/cat "$src_file" | while
        if ! read next_line
        then
            next_line=""
            eof_flag=$TRUE
        fi
        if [ $bof_flag -eq $TRUE ]
        then
            if [ $matched_flag -eq $FALSE ]
            then
                if echo "$prev_line" | grep "$re_prev" > /dev/null && \
                   echo "$cur_line" | grep "$re_remove" > /dev/null && \
                   echo "$next_line" | grep "$re_next" > /dev/null
                then
                    matched_flag=$TRUE
                    echo $cur_line
                    echo $matched_flag > $mstate_file
                fi
            fi
        fi

        if [ $eof_flag -eq $FALSE ]
        then
            /bin/true
        else
            /bin/false
        fi
    do
        prev_line=$cur_line
        cur_line=$next_line
        bof_flag=$TRUE
    done
    matched_flag=`/bin/cat $mstate_file`
    if [ $matched_flag -eq $TRUE ]
    then
        return 0
    else
        return 1
    fi
}

## FUNCTION:    OvCslRemoveMultipleLinesFromFile
## DESCRIPTION: Removes all lines from a file specified by $1 beginning with
##              the first line that matches the regular expression given with $2
##              and ending with the next line that matches the regular
##              expression given with $3.
## PARAMETERS:  $1: File from which the line shall be removed.
##              $2: Regular expression for the line that marks the beginning of
##                  the removal.
##              $3: Regular expression for the line that marks the end of the
##                  removal.
## RETURN VAL:  O:  OK
##              1:  Regular expression in $2 not found.
##              2:  Regular expression in $3 after the first occurence of the
##                  a line matching $2 not found
##              3:  Unable to create temporary file
##              $OVCSL_ERROR_WRITING_FILE, $OVCSL_ERROR_INVALID_PATH,
##              $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO:

OvCslRemoveMultipleLinesFromFile()
{
    [ -e "$1" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$1" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }
    [ -w "$1" ] || { return $OVCSL_ERROR_WRITING_FILE; }

    typeset src_file="$1"
    typeset re_start="$2"
    typeset re_end="$3"
    typeset begin_found=$FALSE
    typeset end_found=$FALSE
    typeset remove_flag=$FALSE
    typeset removal_done=$FALSE
    typeset line=""
    typeset opValue=""

    typeset tmp_file=`OvCslGetOvTemp`/tmp-result-$$
    if ! touch $tmp_file
    then
        return 3
    fi

    typeset begin_state_file=`OvCslGetOvTemp`/tmp-state-begin-$$
    echo $begin_found > $begin_state_file
    typeset end_state_file=`OvCslGetOvTemp`/tmp-state-end-$$
    echo $end_found > $end_state_file

    # Check if begin and end regular expression return correct matches.
    /bin/cat "$src_file" | while read line
    do
        if [ $begin_found -eq $FALSE ]
        then
            opValue=`echo $line | grep "$re_start"`
            if [ -n "${opValue}" ]
            then
                begin_found=$TRUE
                echo $begin_found > $begin_state_file
            fi
        else
            opValue=`echo $line | grep "$re_end"`
            if [ -n "${opValue}" ]
            then
                end_found=$TRUE
                echo $end_found > $end_state_file
            fi
        fi
    done
    begin_found=`/bin/cat $begin_state_file`
    /bin/rm -f $begin_state_file
    end_found=`/bin/cat $end_state_file`
    /bin/rm -f $end_state_file
    if [ $begin_found -eq $FALSE ]
    then
        return 1
    fi
    if [ $end_found -eq $FALSE ]
    then
        return 2
    fi

    # OK, we have found correct boundaries. Remove the lines.
    /bin/cat "$src_file" | while read line
    do
        if [ $remove_flag -eq $TRUE ]
        then
            opValue=`echo $line | grep "$re_end"` 
            if [ -n "${opValue}" ]
            then
                remove_flag=$FALSE
                removal_done=$TRUE
            fi
        else
            opValue=`echo $line | grep "$re_start"` 
            if [ -n "${opValue}" \
                 -a $removal_done -eq $FALSE ]
               then
                remove_flag=$TRUE
            else
                echo $line >> $tmp_file
            fi
        fi
    done

    if ! /bin/mv $tmp_file $src_file
    then
        return $OVCSL_ERROR_WRITING_FILE
    else
        return 0
    fi
}

## FUNCTION:    OvCslGetMultipleLinesFromFile
## DESCRIPTION: Returns all lines from a file specified by $1 beginning with
##              the first line that matches the regular expression given with $2
##              and ending with the next line that matches the regular
##              expression given with $3.
##              LINUX NOTE: If you pipe the output of this function directly you
##              may experience a broken pipe error. Therefore on Linux (bash?)
##              do not write:
##              | OvCslGetMultipleLinesFromFile /tmp/src "start" "end" \
##              |      grep "foo"
##              instead write the output into a file and process this file:
##              | OvCslGetMultipleLinesFromFile /tmp/src "start" "end" >/tmp/out
##              | grep /tmp/out "foo"
##              | /bin/rm -f /tmp/out
## PARAMETERS:  $1: File from which the line shall be read.
##              $2: Regular expression for the line that marks the beginning.
##              $3: Regular expression for the line that marks the end.
## RETURN VAL:  O:  OK
##              1:  Regular expression in $2 not found.
##              2:  Regular expression in $3 after the first occurence of the
##                  a line matching $2 not found
##              3:  On Linux systems: Unable to create temporary file
##              $OVCSL_ERROR_INVALID_PATH,
##              $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO: All lines from the line matching $2 to the line matching $3.

OvCslGetMultipleLinesFromFile()
{
    [ -e "$1" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$1" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }
    [ -w "$1" ] || { return $OVCSL_ERROR_WRITING_FILE; }

    typeset src_file="$1"
    typeset re_start="$2"
    typeset re_end="$3"
    typeset begin_found=$FALSE
    typeset end_found=$FALSE
    typeset retrieve_flag=$FALSE
    typeset retrieval_done=$FALSE
    typeset line=""
    typeset opValue=""

    typeset begin_state_file=`OvCslGetOvTemp`/tmp-state-begin-$$
    echo $begin_found > $begin_state_file
    if [ $? -ne 0 ]
    then
        return 3
    fi
    typeset end_state_file=`OvCslGetOvTemp`/tmp-state-end-$$
    echo $end_found > $end_state_file

    # Check if begin and end regular expression return correct matches.
    /bin/cat "$src_file" | while read line
    do
        if [ $begin_found -eq $FALSE ]
        then
            opValue=`echo $line | grep "$re_start"`
            if [ -n "${opValue}" ]
            then
                begin_found=$TRUE
                echo $begin_found > $begin_state_file
            fi
        else
            opValue=`echo $line | grep "$re_end"`
            if [ -n "${opValue}" ]
            then
                end_found=$TRUE
                echo $end_found > $end_state_file
            fi
        fi
    done
    begin_found=`/bin/cat $begin_state_file`
    /bin/rm -f $begin_state_file
    end_found=`/bin/cat $end_state_file`
    /bin/rm -f $end_state_file
    if [ $begin_found -eq $FALSE ]
    then
        return 1
    fi
    if [ $end_found -eq $FALSE ]
    then
        return 2
    fi

    # OK, we have found correct boundaries. Retrieve the lines.
    /bin/cat "$src_file" | while read line
    do
        if [ $retrieve_flag -eq $TRUE ]
        then
            echo $line
            opValue=`echo $line | grep "$re_end"`
            if [ -n "${opValue}" ]
            then
                retrieve_flag=$FALSE
                retrieval_done=$TRUE
            fi
        else
            opValue=`echo $line | grep "$re_start"`
            if [ -n "${opValue}" \
                 -a $retrieval_done -eq $FALSE ]
               then
                retrieve_flag=$TRUE
                echo $line
            fi
        fi
    done

    return 0
}

## FUNCTION:    OvCslRmDir
## DESCRIPTION: Removes a directory and all subdirectories and files in it.
##              Then traverse the directory structure up and remove all super
##              directories that are empty.
## PARAMETERS:  $1: Path to directory to delete
##              $2: [optional]
##                  $TRUE:  Delete directory and all files and subdirectories
##                          in it.
##                  $FALSE: [default] Delete directory only if it is empty.
##              $3: [optional]
##                  $TRUE:  Change working directory to / to prevent a
##                          directory from beeing locked, because it's the
##                          current working directory.
##                  $FALSE: [default] stay in the current working directory.
##                          an empty directory cannot be removed, if it is
##                          the current working directory.
## RETURN VAL:  0:  command successfully executed
##              1:  Unable to delete given directory
##              2:  Directory not found or not a directory
##              3:  $1 is an empty string -> refusing to delete directory.
##              4:  System Error
## RETURN ECHO: First directory that was not empty and could not be deleted.

OvCslRmDir()
{
    typeset directory=$1
    typeset dirbasename
    typeset retval
    typeset RC

    if [ -z "$directory" ]
    then
        return 3
    fi

    if [ ! -d "$directory" ]
    then
        return 2
    fi
    if ! echo "$directory" | grep "^/" > /dev/null
    then
        if echo "$directory" | grep "^\./" > /dev/null
        then
            directory=`echo "$directory" | sed "s/^\.\///"`
        fi
        directory="`pwd`/$directory"
    fi

    if [ $# -eq 3 ]
    then
        if [ $3 -eq $TRUE ]
        then
            cd /
        fi
    fi

    retval=`OvCslCheckMountPoint $directory`
    RC=$?
    if [ ${RC} -ne 0 ]
    then
        return 4
    fi
    
    if [ "x${retval}" = "x$OVCSL_MOUNTPOINT_PLAIN_DIR" ]  && [ ! -h $1 ]
    then
        if [ $# -ge 2 -a "$2" = "$TRUE" ]
        then
            if ! /bin/rm -f -r $directory 2>/dev/null
            then
                return 1
            fi
        else
            if ! /bin/rmdir $directory 2>/dev/null
            then
                return 1
            fi
        fi
    else
        return 1
    fi

    while [ $directory != "" ]
    do
        dirbasename=`basename $directory`
        directory=`echo "$directory" | sed "s/\/${dirbasename}$//"` #NEDIT"
        
        retval=`OvCslCheckMountPoint $directory`
        RC=$?
        if [ ${RC} -ne 0 ]
        then
            return 4
         fi
        
         if [ "x${retval}" = "x$OVCSL_MOUNTPOINT_PLAIN_DIR" ]  && [ ! -h $1 ]
         then
            if ! /bin/rmdir $directory 2>/dev/null
            then
                echo $directory
                return 0
            fi
        else
            echo $directory
            return 0
        fi
    done
    return 0
}

## FUNCTION:    OvCslRmEmptyDir
## DESCRIPTION: Removes a directory and all subdirectories, only if they are
##              empty
## PARAMETERS:  $1: Path to directory to delete
##              $2: [optional]
##                  $TRUE:  Perform check for mountpoints and do not delete
##                          mountpoints. WARNING: This may take a while for a
##                          multiple directories.
##                  $FALSE: [default] Do not perform mountpoint checks. Assume
##                          that every directory is a plain directory.
##                          WARNING: This must not be used if the directory to
##                          be deleted may be or may contain directories that
##                          are mountpoints.
## RETURN VAL:  0:  command successfully executed
##              1:  Directory not found or not a directory
## RETURN ECHO: First directory that was not empty and could not be deleted.

OvCslRmEmptyDir()
{

  typeset retVal;
  typeset pathVal="$1";
  typeset mp_check=${2:-$FALSE}
  
  OvCslRmEmptyDirEx "${pathVal}"  $TRUE  ${mp_check}
  retVal=$?  
  
  return $retVal
}

## FUNCTION:    OvCslRmEmptyDirEx
## 
## DESCRIPTION: Removes a empty directory and optionally subdirectories only if they are
##              empty
##              
## PARAMETERS:  $1: Path of the directory to delete
##              $2: [optional]
##
##                  $TRUE:  [default] is for deleting recursively 
##                          
##                  $FALSE: is for deleting non-recursively 
##
##              $3: [optional]
##              
##                  $TRUE:  Perform check for mountpoints and do not delete
##                          mountpoints. 
##                  $FALSE: [default] Do not perform mountpoint checks. Assume
##                          that every directory is a plain directory.
##
## RETURN VAL:  0:  command successfully executed
##              1:  Directory not found or not a directory
##              2:  If Directory is not empty
##
## RETURN ECHO: First directory that was not empty and could not be deleted.

OvCslRmEmptyDirEx()
{

  typeset isRecurs=${2:-$TRUE}	
  typeset mp_check=${3:-$FALSE}
  typeset retval
  
  if [[ ! -d $1 ]]
  then
    return 1
  fi

  CONTENTS=`ls $1`
  
  if [[ ! -z ${CONTENTS} ]] 
  then  
    #
    # The directory is non-empty
    #
    
    if [ $isRecurs -eq $TRUE ]
    then    
      
      #
      # Recursive is enabled and the direrctory is non-empty
      #
      
      for j in `ls $1`
      do
        NEWDIR=`echo $1"/"$j`
        # check whether it is a directory
        if [[ -d $NEWDIR ]]
        then
          # check whether it is not a link
          if ! [ -h $NEWDIR ]
          then
            # call OvCslRmEmptyDirEx recursively
            OvCslRmEmptyDirEx $NEWDIR $isRecurs $mp_check
          fi  ## fi of if ! [ -h $NEWDIR ]##
        fi  ## fi of if [[ -d $NEWDIR ]]##    
      done
    
    else  ## else of if [ $isRecurs -eq $TRUE ] ##  
      #
      # Recursive is not enabled and the directory is non-empty
      # Return 2
      #
      return 2   
    
    fi  ## fi of if [ $isRecurs -eq $TRUE ]  ##  
  
  fi   ## fi of if [[ ! -z ${CONTENTS} ]]  ##  
  
  if [[ -z ${CONTENTS} ]] 
  then  
    #
    # The directory is empty
    #
  
    if [ $mp_check -eq $TRUE ]
    then
      retval=`OvCslCheckMountPoint $1`
      if [[ "x$retval" = "x$OVCSL_MOUNTPOINT_PLAIN_DIR"  && ! -h $1 ]]
      then
        /bin/rmdir $1 2>/dev/null
      fi
    else
      /bin/rmdir $1 2>/dev/null
    fi
  
  fi   ## [[ -z ${CONTENTS} ]]  ##  
  
  return 0	
}

## FUNCTION:    OvCslGetOvTemp
## DESCRIPTION: Creates the OpenView temporary directory if it does not exist
##              already and returns the temp directory's path.
## PARAMETERS:  - none -
## RETURN VAL:  0: Success
##              1: Unable to create temporary OpenView directory
## RETURN ECHO: Path of temporary directory

OvCslGetOvTemp()
{
    if [ ! -d "$OVCSL_OV_DATA_TMP" ]
    then
        if ! /bin/mkdir -p "$OVCSL_OV_DATA_TMP"
        then
            return 1
        fi
    fi
    echo $OVCSL_OV_DATA_TMP
}

## FUNCTION:    OvCslMakeBackupCopy
## DESCRIPTION: Make a backup copy of a file by following the scheme below:
##              Filename:    foo
##              1. Backup:   foo.ov_backup.1
##              2. Backup:   foo.ov_backup.2
##              3. Backup:   foo.ov_backup.3
##              ...
##              <n>. Backup: foo.ov_backup.<n>
## PARAMETERS:  $1: Source file of which the backup shall be created.
## RETURN VAL:  0: Success
##              $OVCSL_ERROR_READING_FILE:
##                  Source file not found or not readable.
##              $OVCSL_ERROR_WRITING_FILE:
##                  Unable to create backup.
## RETURN ECHO: Path of backup file

OvCslMakeBackupCopy()
{
    typeset source_file=$1
    if [ ! -r $source_file ]
    then
        return $OVCSL_ERROR_READING_FILE
    fi

    # Create name of backup file
    typeset index=1
    typeset backup_file="${source_file}.${OVCSL_FILE_BACKUP_EXT}.${index}"

    while [ -e $backup_file ]
    do
        index=`/usr/bin/expr $index + 1`
        backup_file="${source_file}.${OVCSL_FILE_BACKUP_EXT}.${index}"
    done

    if /bin/cp -f $source_file $backup_file
    then
        echo $backup_file
        return 0
    else
        return $OVCSL_ERROR_WRITING_FILE
    fi
}

## FUNCTION:    OvCslInstallFile
## DESCRIPTION: Installs a file: Copy a file to a final location and sets
##              ownerships and permissions. If the target file is already
##              existing a backup will be created optionaly.
##              If the file will be installed to a non-existent subdirectory/ies
##              it/these will automatically be created.
## PARAMETERS:  $1: Source file
##              $2: Target file (the name of thetarget file, not the name of the
##                  target directory!!!)
##              $3: Owner name
##              $4: Owner group name
##              $5: Permissions in numerical notation
##              $6: [optional] Should a backup be created, if target file is
##                  already existing?
##                  $TRUE:  yes (default)
##                  $FALSE: no
## RETURN VAL:  0:  Success
##              $OVCSL_ERROR_READING_FILE:
##                  Unable to read source file.
##              $OVCSL_ERROR_COPYING_FILE
##                  Unable to copy file from source to target.
##              1:  Unable to set owner.
##              2:  Unable to set owner group.
##              3:  Unable to set permissions.
##              4:  Unable to create backup file.
##              5:  The directory were it should be installed is not existing
##                  and the creation of this directory failed.
## RETURN ECHO:

OvCslInstallFile()
{
    typeset source="$1"
    typeset target="$2"
    typeset target_dir="`OvCslGetSuperDirectory $target`"
    typeset owner="$3"
    typeset group="$4"
    typeset permissions="$5"
    typeset backup="${6:-$TRUE}"

    if [ ! -r "$source" ]
    then
        return $OVCSL_ERROR_READING_FILE
    fi

    if [ $backup -eq $TRUE -a -e "$target" ]
    then
        OvCslMakeBackupCopy "$target" > /dev/null || return 4
    fi

    if [ ! -d "$target_dir" ]
    then
        /bin/mkdir -p "$target_dir" || return 5
    fi

    /bin/cp -f "$source" "$target" 2>/dev/null \
            || return $OVCSL_ERROR_COPYING_FILE
    /bin/chown "$owner" "$target" 2>/dev/null \
            || return 1
    /bin/chgrp "$group" "$target" 2>/dev/null \
            || return 2
    /bin/chmod "$permissions" "$target" 2>/dev/null \
            || return 3
}

## FUNCTION:    OvCslInstallDirectory
## DESCRIPTION: Installs a directory: Create a new directory and set ownerships
##              and permissions for this directory.
##              If the directory will be installed to a non-existent
##              subdirectory/ies it/these will automatically be created.
## PARAMETERS:  $1: Directory
##              $2: Owner name
##              $3: Owner group name
##              $4: Permissions in numerical notation
##              $5: [optional] If directory is existing...
##                  $TRUE:  ...set ownerships and permissions to given values.
##                  $FALSE: ...leave directory as is. (default)
## RETURN VAL:  0:  Success
##              1:  Directory is already existing and $5 is set to false.
##              2:  There is already a file existing with the same path of the
##                  directory, but it is not a directory.
##              3:  Unable to create directory.
##              4:  Unable to set owner.
##              5:  Unable to set owner group.
##              6:  Unable to set permissions.
## RETURN ECHO:

OvCslInstallDirectory()
{
    typeset target="$1"

    typeset owner="$2"
    typeset group="$3"
    typeset permissions="$4"
    typeset reset="${5:-$FALSE}"

    if [ -e "$target" -a ! -d "$target" ]
    then
        return 2
    fi

    if [ ! -d "$target" ]
    then
        /bin/mkdir -p "$target" 2>/dev/null \
                || return 3
    elif [ $reset -eq $FALSE -a -d "$target" ]
    then
        return 1
    fi

    /bin/chown "$owner" "$target" 2>/dev/null \
            || return 4
    /bin/chgrp "$group" "$target" 2>/dev/null \
            || return 5
    /bin/chmod "$permissions" "$target" 2>/dev/null \
            || return 6
}

## FUNCTION:    OvCslInstallLink
## DESCRIPTION: Installs a link: Create a new link and set ownerships for this
##              link.
##              If the link will be installed to a non-existent subdirectory/ies
##              it/these will automatically be created.
##              NOTE: This function does not check, if the link target is
##              existing.
## PARAMETERS:  $1: Link target
##              $2: Link
##              $2: Owner name
##              $3: Owner group name
##              $5: [optional] If link is existing...
##                  $TRUE:  ...set ownerships and link target to given values.
##                  $FALSE: ...leave link as is. (default)
## RETURN VAL:  0:  Success
##              1:  Link is already existing and $5 is set to $FALSE
##              2:  A file with the same path like the link is already existing,
##                  but is not a link.
##              3:  Unable to create link.
##              4:  Unable to set owner.
##              5:  Unable to set owner group.
##              6:  The directory were it should be installed is not existing
##                  and the creation of this directory failed.
## RETURN ECHO:

OvCslInstallLink()
{
    typeset link_tgt="$1"
    typeset link="$2"
    typeset link_dir="`OvCslGetSuperDirectory $link`"
    typeset owner="$3"
    typeset group="$4"
    typeset reset="${5:-$FALSE}"

    if [ ! -d "$link_dir" ]
    then
        /bin/mkdir -p "$link_dir" || return 6
    fi

    if [ -e "$link" -a ! -h "$link" ]
    then
        return 2
    fi

    if [ -h "$link" ]
    then
        if [ $reset -eq $FALSE ]
        then
            return 1
        else
            /bin/rm -f "$link" || return 3
        fi
    fi

    /bin/ln -f -s "$link_tgt" "$link" 2>/dev/null \
            || return 3
    /bin/chown -h "$owner" "$link" 2>/dev/null \
            || return 4
    /bin/chgrp -h "$group" "$link" 2>/dev/null \
            || return 5
}

## FUNCTION:    OvCslReplaceStringInFile
## DESRIPTION:  Replaces all occurences of a string in a file with a string.
##              NOTE: The string must be "sed-safe", e.g. slashes must be
##                    escaped by a backslash character.
## PARAMETERS:  $1: Source file
##              $2: Search string
##              $3: Replace string
## RETURN VAL:  0:  Success
##              1:  sed error (Probably a problem with one of the strings. See
##                  the note above)
##              $OVCSL_ERROR_READING_FILE:
##                  Unable to read file
##              $OVCSL_ERROR_WRITING_FILE
##                  Unable to write file

OvCslReplaceStringInFile()
{
    typeset file=$1
    typeset search_str=$2
    typeset replace_str=`OvCslEscapeSlashes "$3"`

    # Check source and output files
    [ -r $file ] || return $OVCSL_ERROR_READING_FILE

    /bin/cp -f $file $file.$$ || return $OVCSL_ERROR_WRITING_FILE
    /bin/cat $file.$$ | sed "s/$search_str/$replace_str/g" > $file
    typeset ret_val=$?

    /bin/rm -f $file.$$ 2>/dev/null

    return $ret_val
}

## FUNCTION:    OvCslJnlpRemoveHrefFromFile
## DESCRIPTION: Remove ALL HREFs that match the specified pattern *exactly*
##              (case-sensitive) from between those lines that start
##              with the tags "<!-- BEGIN" and "<!-- END" in the file
##              specified.
## PARAMETERS:  $1: HREF to be removed.
##              $2: File from which the HREF specified is to be removed.
## RETURN VAL:  O:  OK. Specified HREF removed successfully.
##              $OVCSL_ERROR_WRITING_FILE, $OVCSL_ERROR_INVALID_PATH,
##              $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO:
OvCslJnlpRemoveHrefFromFile()
{

    [ -e "$2" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$2" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }
    [ -w "$2" ] || { return $OVCSL_ERROR_WRITING_FILE; }

    typeset flag=0
    typeset jnlp_href="$1"
    typeset jnlp_file="$2"
    typeset tmp_file=`OvCslGetOvTemp`/OvCsl_jnlp.$$
    typeset opValue=""

    if [ -r $tmp_file ]
    then
        /bin/rm -f  $tmp_file
    fi

    # Need to set the IFS to just a new-line.
    typeset pIFS=$IFS
    export IFS="
"
    /bin/cat $jnlp_file | while read line
    do
        echo $line >> $tmp_file
        opValue=`echo $line | grep -c "<!-- BEGIN"`
        if [ ${opValue} -eq 1 ]
        then
            flag=1
            while read line
            do
                opValue=`echo $line | grep -c "${jnlp_href}"`
                if [ $flag=1 -a ${opValue} -eq 0 ]
                then
                    echo $line >> $tmp_file
                    opValue=`echo $line | grep -c "<!-- END"`
                    if [ ${opValue} -eq 1 ]
                    then
                        flag=0
                        break
                    fi
                fi
            done
        fi
    done
    export IFS=${pIFS}

    if ! /bin/mv $tmp_file $jnlp_file
    then
        return $OVCSL_ERROR_WRITING_FILE
    else
        return 0
    fi
}

## FUNCTION:    OvCslJnlpRemoveAllHrefsFromFile
## DESCRIPTION: Remove ALL HREFs from between those lines that start
##              with the tags "<!-- BEGIN" and "<!-- END" in the file
##              specified.
## PARAMETERS:  $1: File from which all HREFs are to be removed.
## RETURN VAL:  O:  OK. All HREFs removed successfully.
##              $OVCSL_ERROR_WRITING_FILE, $OVCSL_ERROR_INVALID_PATH,
##              $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO:
OvCslJnlpRemoveAllHrefsFromFile()
{

    [ -r "$1" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$1" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }
    [ -w "$1" ] || { return $OVCSL_ERROR_WRITING_FILE; }

    typeset jnlp_file="$1"
    typeset tmp_file=`OvCslGetOvTemp`/OvCsl_jnlp.$$
    typeset opValue=""
    
    if [ -r $tmp_file ]
    then
        /bin/rm -f  $tmp_file
    fi

    # Change th IFS to just newline character.
    # This maintains the source indentation.
    typeset pIFS=$IFS
    export IFS="
"

    /bin/cat $jnlp_file | while read line
    do
        echo $line >> $tmp_file
        opValue=`echo $line | grep -c "<!-- BEGIN"`
        if [ ${opValue} -gt 0 ]
        then
            while read line
            do
                opValue=`echo $line | grep -c "<!-- END"`
                if [ ${opValue} -gt 0 ]
                then
                    echo $line >> $tmp_file
                    break
                fi
            done
        fi
    done

    # Change the IFS back to original.
    export IFS=${pIFS}

    if ! /bin/mv $tmp_file $jnlp_file
    then
     return $OVCSL_ERROR_WRITING_FILE
    else
         return 0
    fi
}

## FUNCTION:    OvCslJnlpAddHrefToFile
## DESCRIPTION: Add the specified HREF to the specified jnlp file,
##              immediately after the first line that starts with
##              the tag "<!-- BEGIN".
## PARAMETERS:  $1: The HREF to be added.
##              $2: The jnlp file to which the HREF is to be added.
## RETURN VAL:  O:  OK. Specified HREF added successfully.
##              1:  "<!-- BEGIN" tag not found in file specified.
##                  Nowhere to add specified HREF.
##              2:  Unable to create temporary file.
##              $OVCSL_ERROR_WRITING_FILE, $OVCSL_ERROR_INVALID_PATH,
##              $OVCSL_ERROR_FILE_NOT_REGULAR
## RETURN ECHO:
OvCslJnlpAddHrefToFile()
{
    [ -e "$2" ] || { return $OVCSL_ERROR_INVALID_PATH; }
    [ -f "$2" ] || { return $OVCSL_ERROR_FILE_NOT_REGULAR; }
    [ -w "$2" ] || { return $OVCSL_ERROR_WRITING_FILE; }

    typeset jnlp_href="$1"
    typeset jnlp_file="$2"

    # Remove any previous entries that may be present.
    OvCslJnlpRemoveHrefFromFile "${jnlp_href}" "${jnlp_file}"

    # Performing functionality of OvCslAddLineToFile because
    # OvCslAddLineToFile function removes any/all indentation
    # when writing to the target file. We need to preserve any
    # /all indentation from the source file.
    typeset src_file="${jnlp_file}"
    typeset add_line="${jnlp_href}"
    typeset re_prev="<!-- BEGIN"
    typeset re_next=".*"

    typeset prev_line=""
    typeset cur_line=""
    typeset matched_flag=$FALSE
    typeset eof_flag=$FALSE

    typeset tmp_file=`OvCslGetOvTemp`/tmp-result-$$
    if ! touch $tmp_file
    then
        return 2
    fi

    typeset mstate_file=`OvCslGetOvTemp`/tmp-state-$$
    echo $matched_flag > $mstate_file

    # OK, the user has specified start and/or end tags.
    # Set the IFS value because we dont want to lose initial indentations.
    typeset pIFS=$IFS
    export IFS="
"
    /bin/cat "$src_file" | while
        if ! read cur_line
        then
            cur_line=""
            eof_flag=$TRUE
        fi

        if [ $matched_flag  -eq $FALSE ]
        then
            if echo "$prev_line" | grep "$re_prev" > /dev/null && echo "$cur_line" | grep "$re_next" > /dev/null
            then
                echo "$add_line" >> $tmp_file
                if [ $eof_flag -eq $FALSE ]
                then
                    echo "$cur_line" >> $tmp_file
                fi
                matched_flag=$TRUE
                echo $matched_flag > $mstate_file
            else
                if [ $eof_flag -eq $FALSE ]
                then
                    echo "$cur_line" >> $tmp_file
                fi
            fi
        else
            if [ $eof_flag -eq $FALSE ]
            then
                echo "$cur_line" >> $tmp_file
            fi
        fi

        if [ $eof_flag -eq $FALSE ]
        then
            /bin/true
        else
            /bin/false
        fi
    do
        prev_line=$cur_line
    done
    
    # Set the IFS value back to original.
    export IFS=${pIFS}

    matched_flag=`/bin/cat $mstate_file`
    /bin/rm -f $mstate_file
    if ! /bin/mv $tmp_file $src_file
    then
        return $OVCSL_ERROR_WRITING_FILE
    else
        if [ $matched_flag -eq $TRUE ]
        then
            return 0
        else
            return 1
        fi
    fi
}

## FUNCTION:    OvCslEscapeSlashes
## DESCRITPION: Escape slash character for escaping file system paths for use
##              with sed.
## PARAMETERS:  $1: Input string
## RETURN ECHO: Escaped string
OvCslEscapeSlashes()
{
    echo -e $1 | sed 's/\//\\\//g'
}                      

##FUNCTION:      OvCslIsSELinuxEnabled 
## DESCRPTION:   Checks for SELinux enabled or not 
## PARAMETERS:   - none -
## RETURN VAL:   0: If it is SELinux enabled  
##               1: If it is disabled

OvCslIsSELinuxEnabled()
{
    [ ! -d /etc/selinux ] && return 1

    [ ! -f /etc/selinux/config ] && return 1

    typeset -i lcount=`grep -c -e '^ *SELINUX=disabled' /etc/selinux/config`
    [ $lcount -ne 0 ] && return 1

    typeset -i lcount=`grep -c -e '^ *SELINUX=enforcing' -e '^ *SELINUX=permissive' /etc/selinux/config`
    [ $lcount -ne 0 ] && return 0
}

#
# Platform abstraction functions
#

## FUNCTION:     OvCslGetOsVendor
## DESCRIPTION:  Returns the name of the vendor of the OS. On Linux systems this
##               is the name of the distributor
## PARAMETERS:   - none -
## RETURN VAL:   0:  Vendor name is known
##               1:  Unknown vendor. Function returns output of uname -s
## RETURN ECHO:  One of the following strings:
##               "IBM", "HP", "Sun", "SuSE", "RedHat",
##               "Debian", "@VENDOR_UNKNOWN@" or the output of uname -s for
##               all other platforms

OvCslGetOsVendor()
{
    case "`/bin/uname -s`" in
        "AIX")
            echo "IBM"
            ;;
        "HP-UX")
            echo "HP"
            ;;
        "Linux")
            if [ -f /etc/SuSE-release ]; then
                echo "SuSE"
            elif [ -f /etc/debian_version ]; then
                echo "Debian"
            elif [ -f /etc/redhat-release ]; then
                 echo "RedHat"
            elif [ -f /etc/turbolinux-release ]; then
                 echo "TurboLinux"
            elif [ -d /etc/vmware ]; then
                 echo "VMware"
            elif [ -f "/etc/system-release" ]; then
                 echo "AmazonLinux"
            else
               
                echo "@VENDOR_UNKNOWN@"
                return 1
            fi
            ;;
        "OSF1")
            echo "Compaq"
            ;;
        "SunOS")
            echo "Sun"
            ;;
        *)
            /bin/uname -s
            return 1
            ;;
    esac
    return 0
}

## FUNCTION:    OvCslGetOsMajorVersion
## DESCRIPTION: Returns the major OS version number. Any unimportant parts
##              of the full version number will be stripped, e.g. if uname -r
##              returns "2.4.16-4GB" on a SuSE Linux system, this function will
##              return "2" as major version number. On HP-UX "B.11.20" will be
##              returned as "11". On Sun Solaris "5.8" will become "8" (NOTE:
##              "2.6" will become "6" as well).
##              This can be used for comparing the major version number with
##              the shell test command
## PARAMETERS:  - none -
## RETURN VAL:  0
##              1:  Unknown platform
## RETURN ECHO: Version number of the OS as described above.

OvCslGetOsMajorVersion()
{
    case "`/bin/uname -s`" in
        "AIX")
            @OSLEVEL@ | sed 's/^\([0-9]*\)\..*/\1/'
            ;;
        "HP-UX")
            /bin/uname -r | sed 's/^[A-Z]\.\([0-9]*\).*/\1/'
            ;;
        "Linux")
            /bin/uname -r | sed 's/^\([0-9]*\)\..*/\1/'
            ;;
        "OSF1")
            /bin/uname -r | sed 's/V\([0-9]*\)\.[0-9]*$/\1/'
            ;;
        "SunOS")
            /bin/uname -r | sed 's/[0-9]*\.\([0-9]*\).*/\1/'
            ;;
        *)
            return 1
            ;;
    esac
    return 0
}

## FUNCTION:    OvCslGetOsMinorVersion
## DESCRIPTION: Returns the first minor OS version number. Any unimportant
##              parts of the output of uname -s will be stripped, e.g. if
##              uname -s returns "2.4.16-4GB" on a SuSE Linux system, this
##              return "4" as minor version number. On HP-UX "B.11.11" will be
##              function will return "20". On Sun Solaris "5.8" this function
##              will return with a value of 1.
##              This can be used for comparing the minor version number with
##              the shell test command.
## PARAMETERS:  - none -
## RETURN VAL:  0
##              1:  No minor version number available
## RETURN ECHO: Minor version number of the OS as described above.

OvCslGetOsMinorVersion()
{
    case "`/bin/uname -s`" in
        "AIX")
            @OSLEVEL@ | sed 's/^[0-9]*\.\([0-9]*\)\..*$/\1/'
            ;;
        "HP-UX")
            /bin/uname -r | sed 's/^[A-Z]*\.[0-9]*\.\([0-9]*\).*/\1/'
            ;;
        "Linux")
            /bin/uname -r | sed 's/.[0-9]*\.\([0-9]*\)\..*/\1/'
            ;;
        "OSF1")
            /bin/uname -r | sed 's/V[0-9]*\.\([0-9]*\)$/\1/'
            ;;
        "SunOS")
            return 1
            ;;
        *)
            return 1
            ;;
    esac
    return 0
}

## FUNCTION:    OvCslGetOsVersion
## DESCRIPTION: Returns the OS version number with major and minor (if
##              available) version number.
## PARAMETERS:  - none -
## RETURN VAL:  0
## RETURN ECHO: Version number of the OS as described above.

OvCslGetOsVersion()
{
    if OvCslGetOsMinorVersion >/dev/null; then
        echo "`OvCslGetOsMajorVersion`.`OvCslGetOsMinorVersion`"
    else
        OvCslGetOsMajorVersion
    fi
}

## FUNCTION:    OvCslAddInitScript
## DESCRIPTION: Add a given init script to the systems init process by copying a
##              given script to the system init script directory and creating
##              links to it in the according runlevels. The owner and
##              permissions will be set according to the system guidelines.
##              NOTE: This function requires root privileges.
## PARAMETERS:  $1: Path of the init script that will be copied to the system
##                  init script directory
##              $2: Runlevels in which the script shall be started. You can use
##                  one of these platform independent variables:
##                    - "$OVCSL_RC_NO_NETWORK"
##                      Runlevel with no active network
##                    - "$OVCSL_RC_WITH_NETWORK"
##                      Runlevel with running network (+ runlevel 5 on Linux)
##                  To specify multiple start runlevels specify a
##                  space-separated list of runlevels, e.g. to start a service
##                  runlevel 3 and 5 use "3 5" or "$OVCSL_RC_WITH_NETWORK".
##                  NOTE: $OVCSL_RC_WITH_NETWORK contains a list of runlevel 3
##                  and 5 on Linux and must be embraced with quotes.
##              $3: Start index number (2 digits, a zero will be appended on
##                  platforms that are using 3 digits index numbers)
##              $4: Stop index number (2 digits, a zero will be appended on
##                  platforms that are using 3 digits index numbers)
## RETURN VAL:  0:  Function completed successfully
##              1:  Unable to complete function successfully due to file system
##                  problems.
##              2:  Unsupported Linux distribution
##              3:  Invalid runlevel specified
##              4:  Given init script does not exist
##              5:  Links are already existing in the runlevel directories or
##                  unable to create links.
##              6:  At least one runlevel directory is not existing. Links were
##                  created in all other directories however.
## RETURN ECHO:
## EXAMPLE:     The following examples creates an init script for an Apache web
##              server supplied by an OV product and adds it to the system init
##              process:
##              | init_script=`OvCslMakeInitScript \
##              |                         "ovapache" \
##              |                         "/opt/OV/httpd/bin/apachectl start" \
##              |                         "/opt/OV/httpd/bin/apachectl stop" \
##              |                         "/opt/OV/httpd/bin/apachectl restart"`
##              | if ! OvCslAddInitScript $init_script \
##              |                         $OVCSL_RC_WITH_NETWORK \
##              |                         90 \
##              |                         01
##              | then
##              |     echo "ERROR: Unable to add init script $init_script" 1>&2
##              |     exit 1
##              | fi
##              | # We do not need the generated script anymore
##              | rm -f $init_script

OvCslAddInitScript()
{
    typeset scriptname=`basename $1`
    typeset start_rcs=$2
    typeset rc_script_dir
    typeset rl_dir
    case "`OvCslGetOsVendor`" in
        "Debian")
            rc_script_dir=/etc/init.d
            rl_dir=/etc/[email protected]
            ;;
        "RedHat")
            rc_script_dir=/etc/rc.d/init.d
            rl_dir=/etc/rc.d/[email protected]
            ;;
        "SuSE")
            rc_script_dir=/etc/init.d
            rl_dir=/etc/init.d/[email protected]
            ;;
        "TurboLinux")
            rc_script_dir=/etc/init.d
            rl_dir=/etc/[email protected]
            ;;
        "VMware")
            rc_script_dir=/etc/rc.d/init.d
            rl_dir=/etc/rc.d/[email protected]
            ;;   
        "AmazonLinux")
            rc_script_dir=/etc/rc.d/init.d
            rl_dir=/etc/rc.d/[email protected]
            ;;
        *)
            return 2;
    esac
    typeset start_index="$3"
    typeset stop_index="$4"
    typeset rc
    typeset link_name
    typeset missing_dir_flag=$FALSE
    typeset cur_rl_dir=""
    
    if [ ! -f $1 ]
    then
        return 4
    fi

    if ! /bin/cp -f "$1" "$rc_script_dir/$scriptname" 2>/dev/null
    then
        return 1
    fi

    # SuSE:    Link start script in start_runlevel dir
    #          Link stop script in start_runlevel
    # RedHat, TurboLinux, Debian:
    #          Link start script in start_runlevel dir
    #          Link stop script in all runlevels but start runlevels

    /bin/chmod 755 "$rc_script_dir/$scriptname"
    /bin/chown root:root "$rc_script_dir/$scriptname"

    for i in $start_rcs
    do
        if ! echo $i | grep -qs '[0-6]'
        then
            return 3
        fi
    done

    case `OvCslGetOsVendor` in
        "SuSE")
            rc=0
            while [ $rc -le 6 ]
            do
                cur_rl_dir="`OvCslStrInsertParams $rl_dir $rc`"
                if [ -d "$cur_rl_dir" ]
                then
                    if echo " $start_rcs " | grep -qs " $rc "
                    then
                        link_name="$cur_rl_dir/S${start_index}${scriptname}"
                        if [ -e "$link_name" -o -h "$link_name" ]
                        then
                             /bin/rm -f "$link_name";
                        fi 
                        if ! /bin/ln -f -s "$rc_script_dir/$scriptname" "$link_name" 2>/dev/null
                        then
                            return 5
                        fi
                        link_name="$cur_rl_dir/K${stop_index}${scriptname}"
                        if [ -e "$link_name" -o -h "$link_name" ]; then
                             /bin/rm -f "$link_name";
                        fi 
                        if ! /bin/ln -f -s "$rc_script_dir/$scriptname" "$link_name" 2>/dev/null
                        then
                            return 5
                        fi
                    fi
                else
                    missing_dir_flag=$TRUE
                fi  
                rc=`/usr/bin/expr $rc + 1`
            done
            ;;
        *)
            rc=0            
            while [ $rc -le 6 ]
            do
                cur_rl_dir="`OvCslStrInsertParams $rl_dir $rc`"
                if [ -d "$cur_rl_dir" ]
                then
                    if echo " $start_rcs " | grep -qs " $rc "
                    then
                        link_name="$cur_rl_dir/S${start_index}${scriptname}"
                        if [ -e "$link_name" -o -h "$link_name" ]
                        then
                             /bin/rm -f "$link_name";
                        fi 
                        if ! /bin/ln -f -s "$rc_script_dir/$scriptname" "$link_name" 2>/dev/null
                        then
                            return 5
                        fi
                    else
                        link_name="$cur_rl_dir/K${stop_index}${scriptname}"
                        if [ -e "$link_name" -o -h "$link_name" ]
                        then
                             /bin/rm -f "$link_name";
                        fi 
                        if ! /bin/ln -f -s "$rc_script_dir/$scriptname" "$link_name" 2>/dev/null
                        then
                            return 5
                        fi
                    fi
                else
                    missing_dir_flag=$TRUE
                fi  
                rc=`/usr/bin/expr $rc + 1`
            done
            ;;
    esac

    if [ $missing_dir_flag -eq $TRUE ]
    then
        return 6
    else
        return 0
    fi
}

## FUNCTION:    OvCslRemoveInitScript
## DESCRIPTION: Remove a startup script from the system startup script directory
##              and all links from the runlevel directories.
##              NOTE: This function requires root privileges.
## PARAMETERS:  $1: Name of the startup script
##              $2: Start index number (2 digits, a zero will be appended on
##                  platforms that are using 3 digits index numbers)
##              $3: Stop index number (2 digits, a zero will be appended on
##                  platforms that are using 3 digits index numbers)
## RETURN VAL:  0:  Function completed successfully
##              1:  Unable to complete function successfully
## RETURN ECHO:

OvCslRemoveInitScript()
{
    typeset scriptname=`basename $1`
    typeset start_index="$2"
    typeset stop_index="$3"
    typeset file
    typeset rc_script_dir
    typeset rl_dir
    case "`OvCslGetOsVendor`" in
        "Debian")
            rc_script_dir=/etc/init.d
            rl_dir=/etc/[email protected]
            ;;
        "RedHat")
            rc_script_dir=/etc/rc.d/init.d
            rl_dir=/etc/rc.d/[email protected]
            ;;
        "SuSE")
            rc_script_dir=/etc/init.d
            rl_dir=/etc/init.d/[email protected]
            ;;
        "TurboLinux")
            rc_script_dir=/etc/init.d
            rl_dir=/etc/[email protected]
            ;;
        "VMware")
            rc_script_dir=/etc/rc.d/init.d
            rl_dir=/etc/rc.d/[email protected]
            ;;
        "AmazonLinux")
            rc_script_dir=/etc/rc.d/init.d
            rl_dir=/etc/rc.d/[email protected]
            ;;
        *)
            return 2;
    esac
    for file in `find \`OvCslStrInsertParams $rl_dir \*\` | \
               grep [\(S${start_index}\)\(K${stop_index}\)]${scriptname}$`; do
        if ! /bin/rm -f $file 2>/dev/null; then
            return 1
        fi
    done

    if ! /bin/rm -f "$rc_script_dir/$scriptname" 2>/dev/null; then
        return 1
    fi
    return 0
}

## FUNCTION:    OvCslMakeInitScript
## DESCRIPTION: Creates a default init script based on given start, stop and
##              restart commands and returns the path to the generated file in
##              the OpenView temporary directory.
##              NOTE: - This function requires root privileges.
## PARAMETERS:  $1: Name of the startup script (just script name, no full path)
##              $2: Start command
##              $3: Stop command
##              $4: [optional] Restart command. Default is to run the stop
##                  and then the start command.
##              $5: [optional] Name of the service that is displayed in the
##                  start and stop message. Defaults to the name of the init
##                  script.
## RETURN VAL:  0:  Function completed successfully
##              1:  Unable to write init script.
## RETURN ECHO: Path to the init script.
## EXAMPLE:     The following examples creates an init script for an Apache web
##              server supplied by an OV product and adds it to the system init
##              process:
##              | init_script=`OvCslMakeInitScript \
##              |                         "ovapache" \
##              |                         "/opt/OV/httpd/bin/apachectl start" \
##              |                         "/opt/OV/httpd/bin/apachectl stop" \
##              |                         "/opt/OV/httpd/bin/apachectl restart" \
##              |                         "OpenView Apache Web Server"`
##              | if ! OvCslAddInitScript $init_script \
##              |                         "$OVCSL_RC_WITH_NETWORK" \
##              |                         90 \
##              |                         01
##              | then
##              |     echo "ERROR: Unable to add init script $init_script" 1>&2
##              |     exit 1
##              | fi
##              | # We do not need the generated script anymore
##              | rm -f $init_script

OvCslMakeInitScript()
{
    typeset init_script_name=$1
    typeset start_command=$2
    typeset stop_command=$3
    typeset restart_command="${4:-\$0 stop; \$0 start}"
    typeset service_name="${5:-$init_script_name}"
    
    typeset init_script_file="`OvCslGetOvTemp`/$init_script_name"

    /bin/cat > $init_script_file << INIT_SCRIPT_FILE
#!/bin/sh
# This is a generated script for starting, stopping and restarting a service.
#
# USAGE: $init_script_name start|stop|restart
#
#        start:   Starts the service
#        stop:    Stops the service
#        restart: Restarts the service
#
# (c) Copyright 2017 Hewlett-Packard Enterprise Development Company, L.P.

usage()
{
    echo "USAGE: $init_script_name start|stop|restart" 1>&2
    exit 1
}

start_service()
{
    $start_command
    return \$?
}

stop_service()
{
    $stop_command
    return \$?
}

restart_service()
{
    $restart_command
    return \$?
}

if [ \$# -ne 1 ]; then
    usage
fi

case \$1 in
    start)
        echo "Starting $service_name..."
        start_service
        exit \$?
        ;;
    stop)
        echo "Stopping $service_name..."
        stop_service
        exit \$?
        ;;
    restart)
        restart_service
        exit \$?
        ;;
    *)
        usage
        ;;
esac
INIT_SCRIPT_FILE

    if [ $? -ne 0 ]; then
        return $1
    else
        /bin/chmod +x $init_script_file
        echo $init_script_file
        return 0
    fi
}

## FUNCTION:    OvCslMakeConditionalInitScript
## DESCRIPTION: Creates a default init script based on given start, stop and
##              restart commands and returns the path to the generated file in
##              the OpenView temporary directory.
##              The startup of this script can be enabled/disabled
##              NOTE: - This function requires root privileges.
##                    - Installation of XPL config binaries ovconfget and
##                      ovconfchg is required.
## PARAMETERS:  $1: Name of the startup script (just script name, no full path)
##              $2: XPL config namespace of the attribute that enables/disables 
##                  the service.
##              $3: XPL config attribute name that enables/disables the service.
##              $4: Start command
##              $5: Stop command
##              $6: [optional] Restart command. Default is to run the stop
##                  and then the start command.
##              $7: [optional] Name of the service that is displayed in the
##                  start and stop message. Defaults to the name of the init
##                  script.
## RETURN VAL:  0:  Function completed successfully
##              1:  Unable to write init script.
## RETURN ECHO: Path to the init script.
## EXAMPLE:     The following examples creates an init script for an Apache web
##              server supplied by an OV product and adds it to the system init
##              process:
##              | init_script=`OvCslMakeInitScript \
##              |                         "ovapache" \
##              |                         "/opt/OV/httpd/bin/apachectl start" \
##              |                         "/opt/OV/httpd/bin/apachectl stop" \
##              |                         "/opt/OV/httpd/bin/apachectl restart" \
##              |                         "OpenView Apache Web Server"`
##              | if ! OvCslAddInitScript $init_script \
##              |                         $OVCSL_RC_WITH_NETWORK \
##              |                         90 \
##              |                         01
##              | then
##              |     echo "ERROR: Unable to add init script $init_script" 1>&2
##              |     exit 1
##              | fi
##              | # We do not need the generated script anymore
##              | rm -f $init_script

OvCslMakeConditionalInitScript()
{
    typeset init_script_name=$1
    typeset namespace=$2
    typeset attribute=$3
    typeset start_command=$4
    typeset stop_command=$5
    typeset restart_command="${6:-\$0 stop; \$0 start}"
    typeset service_name="${7:-$init_script_name}"
    
    typeset init_script_file="`OvCslGetOvTemp`/$init_script_name"

    /bin/cat > $init_script_file << INIT_SCRIPT_FILE
#!/bin/sh
# This is a generated script for starting, stopping and restarting a service.
#
# USAGE: $init_script_name start|stop|restart
#
#        start:   Starts the service
#        START:   Starts the service manually
#        stop:    Stops the service
#        STOP:    Stops the service manually
#        restart: Restarts the service
#        enable:  Enable the service to be started
#        disable: Disable the service.
#
# (c) Copyright 2017 Hewlett-Packard Enterprise Development Company, L.P.

SCRIPT_NAME="\$0"
NAMESPACE="$namespace"
ATTRIBUTE="$attribute"
SERVICE_NAME="$service_name"

usage()
{
    echo "USAGE: $init_script_name start|stop|restart|START|STOP|enable|disable" 1>&2
    exit 1
}

start_service()
{
    if [ "\`$OVCSL_OV_BIN/ovconfget \$NAMESPACE \$ATTRIBUTE\`" = "true" ]
    then
       $start_command
        return \$?
    else
        echo "The service \$SERVICE_NAME has been disabled. Please run the command '\$SCRIPT_NAME enable' to enable it or use '\$SCRIPT_NAME [START|STOP]' to start or stop the service manually."
    fi
}

stop_service()
{
    if [ "\`$OVCSL_OV_BIN/ovconfget \$NAMESPACE \$ATTRIBUTE\`" = "true" ]
    then
        $stop_command
        return \$?
    else
        echo "The service \$SERVICE_NAME has been disabled. Please run the command '\$SCRIPT_NAME enable' to enable it or use '\$SCRIPT_NAME [START|STOP]' to start or stop the service manually."
    fi
}

restart_service()
{
    if [ "\`$OVCSL_OV_BIN/ovconfget \$NAMESPACE \$ATTRIBUTE\`" = "true" ]
    then
        $restart_command
        return \$?
    else
        echo "The service \$SERVICE_NAME has been disabled. Please run the command '\$SCRIPT_NAME enable' to enable it or use '\$SCRIPT_NAME [START|STOP]' to start or stop the service manually."
    fi
}

enable_service()
{
    if ! $OVCSL_OV_BIN/ovconfchg -ns \$NAMESPACE -set \$ATTRIBUTE true
    then
        echo "Unable to set the required settings to enable the service \$SERVICE_NAME." 1>&2
        return 1
    else
        echo  "The service \$SERVICE_NAME is now enabled and will be started during the next bootup."
        return 0
    fi
}

disable_service()
{
    if ! $OVCSL_OV_BIN/ovconfchg -ns \$NAMESPACE -set \$ATTRIBUTE false
    then
        echo "Unable to set the required settings to disable the service \$SERVICE_NAME." 1>&2
        return 1
    else
        echo  "The service \$SERVICE_NAME is now disabled and will not be started during the next bootup."
        return 0
    fi
}

if [ \$# -ne 1 ]; then
    usage
fi

case \$1 in

    start)
        echo "Starting \$SERVICE_NAME..."
        start_service
        exit \$?
        ;;
        
    stop)
        echo "Stopping \$SERVICE_NAME..."
        stop_service
        exit \$?
        ;;
        
    restart)
        restart_service
        exit \$?
        ;;

    START)
        $start_command
        exit \$?
        ;; 

    STOP)
        $stop_command
        exit \$?
        ;; 
               
    enable)
        enable_service
        exit \$?
        ;;
        
    disable)
        disable_service
        exit \$?
        ;;
                
    *)
        usage
        ;;
esac
INIT_SCRIPT_FILE

    if [ $? -ne 0 ]; then
        return $1
    else
        /bin/chmod +x $init_script_file
        echo $init_script_file
        return 0
    fi
}

## FUNCTION:    OvCslControlInitScript
## DESCRIPTION: Send start, stop and restart commands to scripts in the init.d
##              directory.
## PARAMETERS:  $1: Name of init script
##              $2: start|stop|restart
## RETURN VAL:  Return value of init script or one of the following:
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Init script not found
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  No permission to execute init script

OvCslControlInitScript()
{

    case `OvCslGetOsVendor` in
        "Debian")
            typeset rc_script_dir=/etc/init.d
            ;;
        "RedHat")
            typeset rc_script_dir=/etc/rc.d/init.d
            ;;
        "SuSE")
            typeset rc_script_dir=/etc/init.d
            ;;
        "TurboLinux")
            typeset rc_script_dir=/etc/init.d
            ;;
        "VMware")
            typeset rc_script_dir=/etc/rc.d/init.d
            ;;
        *)
            OvCslGetOsVersion
    esac
    [ -f "$rc_script_dir/$1" ] || { return $OVCSL_ERROR_FILE_NOT_FOUND; }
    [ -x "$rc_script_dir/$1" ] || { return $OVCSL_ERROR_FILE_NOT_EXECUTABLE; }
    
    "$rc_script_dir/$1" $2
    return $?
}

## FUNCTION:    OvCslGetOsVendorRelease
## DESCRIPTION: Returns the release number of the OS. On Linux systems this is
##              the release number of the distribution. On other systems the
##              release number is the same as the OS version number from the
##              function OvCslGetOsVersion.
## PARAMETERS:  - none -
## RETURN VAL:  0
## RETURN ECHO: Release number of the OS as described above.

OvCslGetOsVendorRelease()
{
    case `OvCslGetOsVendor` in
        "Debian")
            echo `/bin/cat /etc/debian_version`
            ;;
        "RedHat")
            set `/bin/cat /etc/redhat-release | tr '()' ' ' `
            echo $5
            ;;
        "SuSE")
            set `/bin/cat /etc/SuSE-release | grep VERSION`
            echo $2
            ;;
        "TurboLinux")
            set `/bin/cat /etc/turbolinux-release | tr '()' ' ' `
            echo $4
            ;;
        "VMware")
            echo `/bin/cat /etc/issue | grep VMware | awk '{print $4}'`
            ;;
        *)
            OvCslGetOsVersion
    esac
}

## FUNCTION:    OvCslControlInetd
## DESCRIPTION: Start, stop and restart the inetd (xinetd on RedHat systems)
##              daemon.
## PARAMETERS:  $1: start | stop | restart
## RETURN VAL:  0:  Success
##              ?:  Return value of system start|stop|restart command
## RETURN ECHO: Output of system dependend inetd start|stop|restart command

OvCslControlInetd()
{
    case `OvCslGetOsVendor` in
        "SuSE")
            case $1 in
                start)
                    /sbin/init.d/inetd start
                    ;;
                stop)
                    /sbin/init.d/inetd stop
                    ;;
                restart)
                    /sbin/init.d/inetd restart
                    ;;
                *)
                    echo "INTERNAL ERROR: Invalid parameter." 1>&2
                    exit $OVCSL_ERROR_USAGE
                    ;;
            esac
            ;;
        "RedHat")
            case $1 in
                start)
                    /etc/init.d/xinetd start
                    ;;
                stop)
                    /etc/init.d/xinetd stop
                    ;;
                restart)
                    /etc/init.d/xinetd restart
                    ;;
                *)
                    echo "INTERNAL ERROR: Invalid parameter." 1>&2
                    exit $OVCSL_ERROR_USAGE
                    ;;
            esac
            ;;
        "TurboLinux")
            case $1 in
                start)
                    /etc/init.d/xinetd start
                    ;;
                stop)
                    /etc/init.d/xinetd stop
                    ;;
                restart)
                    /etc/init.d/xinetd restart
                    ;;
                *)
                    echo "INTERNAL ERROR: Invalid parameter." 1>&2
                    exit $OVCSL_ERROR_USAGE
                    ;;
            esac
            ;;
        "Debian")
            case $1 in
                start)
                    /etc/init.d/inetd start
                    ;;
                stop)
                    /etc/init.d/inetd stop
                    ;;
                restart)
                    /etc/init.d/inetd restart
                    ;;
                *)
                    echo "INTERNAL ERROR: Invalid parameter." 1>&2
                    exit $OVCSL_ERROR_USAGE
                    ;;
            esac
            ;;
         "VMware")
              case $1 in
                  start)
                      /etc/init.d/xinetd start
                      ;;
                  stop)
                      /etc/init.d/xinetd stop
                      ;;
                  restart)
                      /etc/init.d/xinetd restart
                      ;;
                   *)
                       echo "INTERNAL ERROR: Invalid parameter." 1>&2
                       exit $OVCSL_ERROR_USAGE
                      ;;
              esac
              ;;
        "AmazonLinux")
            case $1 in
                start)
                    /etc/init.d/xinetd start
                    ;;
                stop)
                    /etc/init.d/xinetd stop
                    ;;
                restart)
                    /etc/init.d/xinetd restart
                    ;;
                *)
                    echo "INTERNAL ERROR: Invalid parameter." 1>&2
                    exit $OVCSL_ERROR_USAGE
                    ;;
            esac
            ;;			  
 esac
    return $?
}

## FUNCTION:    OvCslQueryInstalledPackages
## DESCRIPTION: Returns a list of installed packages that were installed by the
##              native installer.
##              On Debian Linux this function returns a list of a all installed
##              DEB packages and, if rpm is present, a list of RPM packages.
## PARAMETERS:  - none -
## RETURN VAL:
## RETURN ECHO: List of installed packages

OvCslQueryInstalledPackages()
{
    case `OvCslGetOsVendor` in
        "Debian")
            /usr/bin/dpkg -l | grep ^ii \
                      | sed "s/  */@/g" \
                      | cut -d @ -f 2
            if [ -x /usr/bin/rpm ]
            then
                /usr/bin/rpm -qa --queryformat="%{NAME}\n"
            fi
            ;;
        *)
            /bin/rpm -qa --queryformat="%{NAME}\n"
            ;;
    esac
}

## FUNCTION:    OvCslGetInstalledPackageVersion
## DESCRIPTION: Returns the version of an installed package.
##              NOTE ON DEBIAN: The function searches for the version number
##              of a DEB packages. If no DEB package can be found, it searches
##              the RPM database, if RPM is available.
##              NOTE ON TRU64: On Tru64 platforms the native installer does not
##              provide a special field for the version. Therefore OV packages
##              must have the version included at the end of the description
##              field:
##              <description> Version <version number>
## PARAMETERS:  $1: Name of package
## RETURN VAL:  0:  Success
##              1:  Given package name is not installed.
## RETURN ECHO: Version of installed package

OvCslGetInstalledPackageVersion()
{
   typeset packagecount=`OvCslQueryInstalledPackages | grep -c "^$1$"`
   if [[ packagecount -eq 0 ]]; then
      return 1
   fi	  
    case `OvCslGetOsVendor` in
        "Debian")
            typeset version=""
            version=`/usr/bin/dpkg -l | sed "s/  */@/g" \
                               | grep "^ii@${1}@" \
                               | cut -d @ -f 3` 2>/dev/null
            if [-z "$version"] && [ -x /usr/bin/rpm ]
            then
                /usr/bin/rpm -q --queryformat="%{VERSION}" "$1"
            fi
            echo "$version"
            ;;
        *)
            /bin/rpm -q --queryformat="%{VERSION}" "$1"
            ;;
    esac
    return 0
}

## FUNCTION:    OvCslCreateOvProfile
## DESCRIPTION: This function creates an initial profile
##              By default [i.e. without any argument ] the file ovprofile 
##              in the directory <Data Dir>/conf/ will be created if the file does not 
##              exist,
##
##              If the file name is mentioned as argument [ with full path ],
##              the specified file will be created if it does not exist
##
##              This file can be sourced by the user to get OpenView
##              related environment settings, like PATH and MANPATH.
##
##              The required environment settings that are needed by OV components 
##              can be added to this file.
##
##              NOTE: - This function requires root privileges.
## PARAMETERS: 
##              $1 :(optional) The file name with full path
##                  [ If the file name is not specified , the  default file is
##                   <Data Dir>/conf/ovprofile ]
##
## RETURN VAL:  0:  Success
##              1:  Unable to create directory /var/opt/OV/conf
##              2:  Unable to create the file
##              $OVCSL_ERROR_OPENING_FILE if the file is not able to be opened
##              $OVCSL_ERROR_USAGE         if the syntax error has occured
## RETURN ECHO:

OvCslCreateOvProfile()
{
     
     [ $# -le 1 ] || { echo "INTERNAL ERROR: Wrong number of parameters." 1>&2; exit $OVCSL_ERROR_USAGE; }    
     
     if [ $# -eq 0 ]
       then
          typeset profile_file="$OVCSL_OV_DATA_CONF/ovprofile" 
       else           
          typeset profile_file=`OvCslStrTrim "$1"`    
           if [ "X${profile_file}" = "X" ]
               then
                 exit $OVCSL_ERROR_OPENING_FILE;
           fi    
           
     fi
    
    # Create the OV conf directory if not already existing
    if [ ! -d "$OVCSL_OV_DATA_CONF" ]
    then
        /bin/mkdir -p $OVCSL_OV_DATA_CONF || return 1
    fi

    # Is $profile_file already existing?
    if [ ! -f "$profile_file" ]
    then
        # $profile_file is not existing yet -> create it
        /bin/cat >> "$profile_file" << END_OF_OVPROFILE
# Profile for OpenView system environment settings.
# Source this file to get OpenView related environment variables:
# . $profile_file

END_OF_OVPROFILE
    fi
    return 0
}

## FUNCTION:    OvCslRemoveOvProfile
## DESCRIPTION: Delete the file mentioned. If the file name is not mentined, 
##              the default file name is <Data Dir>/conf/ovprofile
##
##              NOTE: - This function requires root privileges.
## PARAMETERS:  
##              $1 :(optional) The file name with full path
##                  [ If the file name is not specified , the  default file is
##                   <Data Dir>/conf/ovprofile ]
##
## RETURN VAL:  0:  Success
##              $OVCSL_ERROR_DELETING_FILE if the file is not able to be deleted  
##              $OVCSL_ERROR_USAGE         if the syntax error has occured
## RETURN ECHO: 

OvCslRemoveOvProfile()
{
   
   [ $# -le 1 ] || { echo "INTERNAL ERROR: Wrong number of parameters." 1>&2; exit $OVCSL_ERROR_USAGE; }    
   
   if [ $# -eq 0 ] 
       then
          typeset profile_file="$OVCSL_OV_DATA_CONF/ovprofile" 
       else  
          typeset profile_file=`OvCslStrTrim "$1"`    
           if [ "X${profile_file}" = "X" ]
               then
                 exit $OVCSL_ERROR_DELETING_FILE;
           fi    
           
   fi

    # Delete ovprofile
    if [ -e "$profile_file" ]
    then
        /bin/rm -f "$profile_file" || return $OVCSL_ERROR_DELETING_FILE
    fi     
}

## FUNCTION:    OvCslAddEntryToEnvVarList
## DESCRIPTION: Adds a given unique entry to a colon separated list of values to
##              an environment variable that will be set in the given profile
##              file. Examples of environment variables with a colon separated 
##              list are PATH or MANPATH.
##              NOTE: - This function requires root privileges.
##
## PARAMETERS:  $1: Profile file name [ with full path ]
##                  if the file name is empty string [ i.e. " " ], the default file 
##                  name is  <Data Dir>/conf/ovprofile 
##
##              $2: Name of environment variable
##              $3: New entry
## RETURN VAL:  0:  Success
##              1:  Entry is already existing.
##              2:  Cannot create ovprofile using OvCslCreateOvProfile
##              3:  Cannot create backup of profile file
##              $OVCSL_ERROR_WRITING_FILE  Unable to write to profile file
##              $OVCSL_ERROR_USAGE         if the syntax error has occured

OvCslAddEntryToEnvVarList()
{

    [ $# -eq 3 ] || { echo "INTERNAL ERROR: Wrong number of parameters." 1>&2; exit $OVCSL_ERROR_USAGE; }
    typeset profile_file=`OvCslStrTrim "$1"`
    typeset env_var=$2
    typeset entry=$3
    
    # Create the OvProfile, if not already existing
     if [ "X${profile_file}" = "X" ]
      then
        OvCslCreateOvProfile
        profile_file="$OVCSL_OV_DATA_CONF/ovprofile"
      else
        OvCslCreateOvProfile $profile_file
     fi  

    if [ $? -ne 0 ]
    then
        return 2
    fi
       
    # Is the given entry already set?
    typeset existing_content="`/bin/cat $profile_file \
                                              | grep \"^export ${env_var}=\" \
                                              | /usr/bin/head -n1 \
                                              | sed \"s/^export ${env_var}=//\"`"     #`
    if echo ":${existing_content}:" | grep -qs ":${entry}:"
    then
        return 1
    else
        # The given entry is not existing
        if ! typeset ovprofile_backup=`OvCslMakeBackupCopy $profile_file`
        then
            return 3
        fi        
        
        # If the environment variable is already set in ovprofile, append the
        # new entry, else add the new environment variable
        if /bin/cat "$profile_file" | grep -qs "^export ${env_var}="
        then
            # Escape slashes in entry string
            typeset sed_entry=`echo "$entry" | sed 's/\//\\\\\//g'`
            if ! /bin/cat $ovprofile_backup \
                    | sed "s/^\(export ${env_var}=.*\)/\1:${sed_entry}/" \
                    > $profile_file
            then
                /bin/cp -f $ovprofile_backup $profile_file 2>/dev/null
                return $OVCSL_ERROR_WRITING_FILE
            fi            
        else
            OvCslAddLineToFile $profile_file "export ${env_var}=${entry}"
        fi
    fi
}

## FUNCTION:    OvCslRemoveEntryFromEnvVarList
## DESCRIPTION: Removes a given entry from a colon separated list of values of
##              an environment variable that will be set in the given profile
##              file. Examples of environment variables with a colon separated
##              list are PATH or MANPATH.
##              NOTE: - This function requires root privileges.
## PARAMETERS:  $1: Profile file
##              $2: Name of environment variable
##              $3: Entry to be removed
## RETURN VAL:  0:  Success
##              1:  Entry is not existing.
##              2:  ovprofile does not exist or is not writable
##              3:  Cannot create backup of profile file
##              $OVCSL_ERROR_WRITING_FILE:
##                  Unable to write to profile file.

OvCslRemoveEntryFromEnvVarList()
{
    typeset profile_file="$1"
    typeset env_var=$2
    typeset entry=$3
    
    # The profile file does not exist
    if [ ! -w $profile_file ]
    then
        return 2
    fi
       
    # Is the given entry already set?
    typeset existing_content="`/bin/cat $profile_file \
                                              | grep \"^export ${env_var}=\" \
                                              | /usr/bin/head -n1 \
                                              | sed \"s/^export ${env_var}=//\"`" #`
    if echo ":${existing_content}:" | grep -qs ":${entry}:"
    then
        if ! typeset ovprofile_backup=`OvCslMakeBackupCopy $profile_file`
        then
            return 3
        fi        
        
        # Escape slashes in entry string
        typeset sed_entry=`echo "$entry" | sed 's/\//\\\\\//g'`
        if ! /bin/cat $ovprofile_backup \
                    | sed "s/^\(export ${env_var}=.*\)$sed_entry\(.*\)$/\1\2/" \
                    | sed 's/:[ ]*$//' \
                    | sed 's/::/:/' \
                    > $profile_file
        then
            /bin/cp -f $ovprofile_backup $profile_file 2>/dev/null
            return $OVCSL_ERROR_WRITING_FILE
        fi
    else
        return 1
    fi
}

## FUNCTION:    OvCslAddBinaryPath
## DESCRIPTION: Add a path with binaries to the PATH environment variable for
##              all members of the ovadm group to the file
##              $OVCSL_OV_DATA_CONF/@OVADMPROFILE@
##              NOTE: - This function requires root privileges.
## PARAMETERS:  $1: Path to add
## RETURN VAL:  0:  Success
##              - For error codes please refer to OvCslAddEntryToEnvVarList -
## RETURN ECHO: 

OvCslAddBinaryPath()
{
    if [ -d "$1" ]
    then
        typeset path="$1"
    else
        return $OVCSL_ERROR_DIR_NOT_FOUND
    fi
    
    OvCslAddEntryToEnvVarList "$OVCSL_OV_DATA_CONF/ovprofile" "PATH" "\$PATH"
    typeset retval=$?
    if [ $retval -gt 1 ]
    then
        return $retval
    fi
    OvCslAddEntryToEnvVarList "$OVCSL_OV_DATA_CONF/ovprofile" "PATH" "$path" || return $?
}

## FUNCTION:    OvCslRemoveBinaryPath
## DESCRIPTION: Remove a path from the PATH environment variable. 
##              See OvCslAddBinaryPath for more information.
##              NOTE: - This function requires root privileges.
## PARAMETERS:  $1: Path to remove
## RETURN VAL:  0:  Success0:  Success
##              - For error codes please refer to OvCslRemoveEntryFromEnvVarList -
## RETURN ECHO: 

OvCslRemoveBinaryPath()
{
    typeset path="$1"
    
    OvCslRemoveEntryFromEnvVarList "$OVCSL_OV_DATA_CONF/ovprofile" "PATH" "$path" || return $?
}

## FUNCTION:    OvCslAddManPath
## DESCRIPTION: Add a path to the MANPATH environment variable in the file
##              "$OVCSL_OV_DATA_CONF/ovprofile"
##              NOTE: - This function requires root privileges.
## PARAMETERS:  $1: Path to add
## RETURN VAL:  0:  Success
##              - For error codes please refer to OvCslAddEntryToEnvVarList -
## RETURN ECHO: 

OvCslAddManPath()
{
    if [ -d "$1" ]
    then
        typeset path="$1"
    else
        return $OVCSL_ERROR_DIR_NOT_FOUND
    fi
    if [ ! -f /etc/profile.local ] ; then
      touch /etc/profile.local
    fi

    OvCslAddEntryToEnvVarList "$OVCSL_OV_DATA_CONF/ovprofile" "MANPATH" "\$MANPATH"
    typeset retval=$?
    if [ $retval -gt 1 ]
    then
        return $retval
    fi
    OvCslAddEntryToEnvVarList "$OVCSL_OV_DATA_CONF/ovprofile" "MANPATH" "$path" || return $?
}

## FUNCTION:    OvCslRemoveManPath
## DESCRIPTION: Remove a path from the MANPATH environment variable. 
##              See OvCslAddBinaryPath for more information.
##              NOTE: - This function requires root privileges.
## PARAMETERS:  $1: Path to remove
## RETURN VAL:  0:  Success0:  Success
##              - For error codes please refer to OvCslRemoveEntryFromEnvVarList -
## RETURN ECHO: 

OvCslRemoveManPath()
{
    typeset path="$1"
    
    OvCslRemoveEntryFromEnvVarList "$OVCSL_OV_DATA_CONF/ovprofile" "MANPATH" "$path" || return $?
}

## FUNCTION:    OvCslGetQualifiedHostnameOfHost
## DESCRIPTION: Returns the fully qualified hostname from an unqualified
##              hostname.
##              NOTE: DNS must be properly configured on the system and
##                    nslookup must be able to resolve the given hostname
##                    for this function to work.
## PARAMETERS:  $1: Unqualified hostname
## RETURN VAL:  0:  Successfully returned the hostname.
##              >0: An error occurred.
## RETURN ECHO: Fully qualified hostname.

OvCslGetQualifiedHostnameOfHost()
{
    typeset hostname=$1

    /usr/bin/nslookup $hostname 2>/dev/null | grep "Name:" \
                                     | sed 's/^.*Name: *//'
    return $?
}

## FUNCTION:    OvCslGetQualifiedHostname
## DESCRIPTION: Returns the fully qualified hostname of the system on which this
##              function has been launched.
## PARAMETERS:  None
## RETURN VAL:  0:  Successfully returned the hostname.
##              >0: An error occurred.
## RETURN ECHO: Fully qualified hostname.

OvCslGetQualifiedHostname()
{
    OvCslGetQualifiedHostnameOfHost `hostname`
    return $?
}

## FUNCTION:    OvCslCreateJnlpTemplate
## DESCRITPION: Create empty extension jnlp file
## PARAMETERS:  $1:Component Name
## RETURN ECHO:

OvCslCreateJnlpTemplate()
{
       typeset source_file=${OVCSL_OV_WWW}/webstart/$1.jnlp
       typeset target_file=${OVCSL_OV_WWW}/webstart/$1exts.jnlp
       typeset search_title="<\/title>"
       typeset replace_title=" Extension<\/title>"
       typeset search_res="<resources>"
       typeset search_sres="</resources>"
       typeset search_sec="<\/security>"

       /bin/cp -f $source_file $target_file

       OvCslReplaceStringInFile $target_file $search_title $replace_title
       OvCslRemoveMultipleLinesFromFile $target_file $search_res $search_sres
       OvCslAddLineToFile $target_file $search_res $search_sec
       OvCslAddLineToFile $target_file "<j2se version=1.4+/>" $search_res
       OvCslAddLineToFile $target_file "<!-- BEGIN OpenView product component extensions -->" "<j2se version=1.4+/>"
       OvCslAddLineToFile $target_file "<!-- END OpenView product component extensions -->" "<!-- BEGIN OpenView product component extensions -->"
      OvCslAddLineToFile $target_file $search_sres "<!-- END OpenView product component extensions -->"
}

## FUNCTION:    OvCslIsNetPortInUse
## DESCRIPTION: Checks if a network port is already occupied.
## PARAMETERS:  $1: port
## RETURN VAL:  0:  Port is in use
##              1:  Port is not in use
## RETURN ECHO: 

OvCslIsNetPortInUse()
{

    typeset port=$1
    typeset check

    check=`/bin/netstat -an  | awk '{print $4}' | awk -F":" '/:'$port$'/' | /usr/bin/wc -l`

    if [ $check -ne 0 ]
    then
        return 0
    else
        return 1
    fi
}

## FUNCTION:    OvCslCtrlStart
## DESCRIPTION: Start an OV component using L-Core Control.
##              NOTE: L-Core Control must be installed before this function can
##              be used.
## PARAMETERS:  $1: component ID
##              $2: [optional] name of the remote node on which to launch this
##                  action
## RETURN VAL:  Return value of the control CLI.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Control CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE
##                  Control CLI executable not executable.
## RETURN ECHO:

OvCslCtrlStart()
{
    if [ $# -eq 1 ]; then
        [ -e "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
        [ -x "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
        $OVCSL_OV_BIN/ovc -start $1
    else
        [ -e "$OVCSL_OV_BIN/ovrc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
        [ -x "$OVCSL_OV_BIN/ovrc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
        $OVCSL_OV_BIN/ovrc -start $1 -node $2
    fi
}

## FUNCTION:    OvCslCtrlRestart
## DESCRIPTION: Restart an OV component using L-Core Control. The component will
##              only be restarted, if it was already running previously. If the
##              component was not running, it will not be started.
##              NOTE: L-Core Control must be installed before this function can
##              be used.
## PARAMETERS:  $1: component ID
##              $2: [optional] name of the remote node on which to launch this
##                  action
## RETURN VAL:  Return value of the control CLI.
##              1:  Component is not running.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Control CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE
##                  Control CLI executable not executable.
## RETURN ECHO:

OvCslCtrlRestart()
{
    if OvCslCtrlStatus $1 > /dev/null; then
        if [ $# -eq 1 ]; then
            [ -e "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
            [ -x "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
            $OVCSL_OV_BIN/ovc -restart $1
        else
            [ -e "$OVCSL_OV_BIN/ovrc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
            [ -x "$OVCSL_OV_BIN/ovrc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
            $OVCSL_OV_BIN/ovrc -restart $1 -node $2
        fi
    else
        return 1
    fi
}

## FUNCTION:    OvCslCtrlStop
## DESCRIPTION: Stop an OV component using L-Core Control.
##              NOTE: L-Core Control must be installed before this function can
##              be used.
## PARAMETERS:  $1: component ID
##              $2: [optional] name of the remote node on which to launch this
##                  action
## RETURN VAL:  Return value of the control CLI.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Control CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE
##                  Control CLI executable not executable.
## RETURN ECHO:

OvCslCtrlStop()
{
    if [ $# -eq 1 ]; then
        [ -e "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
        [ -x "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
        ps -ef | grep ovcd | grep -v grep >/dev/null || return 0
        $OVCSL_OV_BIN/ovc -stop $1
    else
        [ -e "$OVCSL_OV_BIN/ovrc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
        [ -x "$OVCSL_OV_BIN/ovrc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
        $OVCSL_OV_BIN/ovrc -stop $1 -node $2
    fi
}

## FUNCTION:    OvCslCtrlStopNoStart
##
## DESCRIPTION: Stop an OV component using L-Core Control and do not start the registered 
##              L-Core  components  
##
##              NOTE: L-Core Control must be installed before this function can
##              be used.
##
## PARAMETERS:  $1: [optional] component ID
##              [ If the component id is not mentioned, all the components will be stoped 
##              excpet the registered L-core components ]
##
## RETURN VAL: 
##              Return value will be the return value of 'ovc -stop [<comp id>] -nostart'
##                  
##              $OVCSL_ERROR_FILE_NOT_FOUND:      if the file ovc not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE  if the file ovc not is not executable.
## RETURN ECHO:

OvCslCtrlStopNoStart()
{
  [ -e "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
  [ -x "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE    

  $OVCSL_OV_BIN/ovc -stop $1 -nostart 
  
  typeset retVal=$?
  if [ $retVal -ne 0 ]
  then    
      return $retVal
  fi  
  return $retVal
}

## FUNCTION:    OvCslCtrlStatus
## DESCRIPTION: Return the status of a component controlled by L-Core Control.
##              NOTE: L-Core Control must be installed before this function can
##              be used.
## PARAMETERS:  $1: component ID as it appears in the first column of the output
##                  of 'ovc -status'.
##              $2: [optional] name of the remote node on which to launch this
##                  action
## RETURN VAL:  0: Component is running
##              1: Component is not running
##              2: Component not registered
##              3: Control Core not running
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Control CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE
##                  Control CLI executable not executable.
## RETURN ECHO: "running": Component is running
##              "stopped": Component is not running.

OvCslCtrlStatus()
{
    [ -e "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE

    if $OVCSL_OV_BIN/ovc 1>/dev/null 2>/dev/null
    then  
        if $OVCSL_OV_BIN/ovc | grep -qs "^$1"
        then
            if $OVCSL_OV_BIN/ovc | grep "^$1" | grep -qs "Running$"
            then
                return 0
            else
                return 1
            fi
        else
            return 2
        fi
    else
        return 3
    fi
}

## FUNCTION:    OvCslCtrlKill
## DESCRIPTION: Kill the control core daemon and all controlled components.
##              NOTE: L-Core Control must be installed before this function can
##              be used. This function can only be used on a local node.
## PARAMETERS:  -none-
## RETURN VAL:  Return value of the control CLI.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Control CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE
##                  Control CLI executable not executable.
## RETURN ECHO:

OvCslCtrlKill()
{
    [ -e "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovc" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
    ps -ef | grep ovcd | grep -v grep >/dev/null || return 0
    $OVCSL_OV_BIN/ovc -kill
}

## FUNCTION:    OvCslCtrlCheckRegFile
## DESCRIPTION: Check a registration file for syntactical correctness.
##              NOTE: L-Core Control must be installed before this function can
##              be used.
## PARAMETERS:  $1: Path of registration file.
## RETURN VAL:  Return value of the registration CLI.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Registration CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  Registration CLI executable not executable.
##              $OVCSL_ERROR_READING_FILE:
##                  Registration file not readable.
## RETURN ECHO:

OvCslCtrlCheckRegFile()
{
     [ -e "$OVCSL_OV_BIN/ovcreg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
     [ -x "$OVCSL_OV_BIN/ovcreg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
     [ -r "$1" ] || return $OVCSL_ERROR_READING_FILE
     $OVCSL_OV_BIN/ovcreg -check "$1"
}

## FUNCTION:    OvCslCtrlRegComponent
## DESCRIPTION: Register an OV component.
##              NOTE: L-Core Control must be installed before this function can
##              be used.
## PARAMETERS:  $1: Path of registration file.
## RETURN VAL:  Return value of the registration CLI.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Registration CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  Registration CLI executable not executable.
##              $OVCSL_ERROR_READING_FILE:
##                  Registration file not readable.
## RETURN ECHO:

OvCslCtrlRegComponent()
{
     [ -e "$OVCSL_OV_BIN/ovcreg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
     [ -x "$OVCSL_OV_BIN/ovcreg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
     [ -r "$1" ] || return $OVCSL_ERROR_READING_FILE
     $OVCSL_OV_BIN/ovcreg -add "$1"
}

## FUNCTION:    OvCslCtrlUnregComponent
## DESCRIPTION: Stop and unregister an OV component.
##              NOTE: L-Core Control must be installed before this function can
##              be used.
## PARAMETERS:  $1: component ID
## RETURN VAL:  Return value of the registration CLI.
##              $OVCSL_ERROR_FILE_NOT_FOUND:
##                  Registration CLI executable not found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  Registration CLI executable not executable.
## RETURN ECHO:

OvCslCtrlUnregComponent()
{
     [ -e "$OVCSL_OV_BIN/ovcreg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
     [ -x "$OVCSL_OV_BIN/ovcreg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
     $OVCSL_OV_BIN/ovcreg -del "$1"
}

## FUNCTION:    OvCslXplTrace
## DESCRIPTION: Trace a message using XPL, if tracing is enabled via the
##              environment variable $OVCSL_TRACE.
##              NOTE: XPL must be installed before this function can be used.
## PARAMETERS:  $OVCSL_TRACE:
##                  Anything else than an empty string (e.g. OVCSL_TRACE=1):
##                          Tracing enabled
##                  "" or not set:
##                          Tracing disabled
##              $OVCSL_LOG_APPLICATION:
##                  Name of the application doing the trace
##              $1: Trace message.
##              $2: [optional] Component name doing the trace. Default is
##                  "shell script".
##              $3: [optional] Attributes: One of "info", "warn" or "error" plus
##                  (separated by commas and no whitespace) "developer" and/or
##                  "verbose". See the XPL tracing documentation for more info.
##                  Default is "info"
##              $4: [optional] Category of the trace message. Default is "none".
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  XPL tracing CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  XPL tracing CLI binary is not executable for calling user.
##              Return value of XPL tracing CLI binary.
## RETURN ECHO: 
## EXAMPLES:    | export OVCSL_TRACE=1
##              | export OVCSL_LOG_APPLICATION="MyApp"
##              | OvCslXplTrace MyComp "An informational trace msg"
##              | OvCslXplTrace MyComp "A warning trace msg" warn,verbose
## IMPORTANT : Funcation changed to support HPUX AR. During hot update of HPUX this function will not work

OvCslXplTrace()
{
    if [ ! -z "$OVCSL_TRACE" ]; then
        # For performance reasons run the parameter check only if tracing is
        # enabled.
        if [ -z "$OVCSL_TRACE_FILE" -o -z "$OVCSL_LOG_APPLICATION" ]; then
            echo "INTERNAL ERROR: Trace variables OVCSL_TRACE, OVCSL_TRACE_FILE and OVCSL_LOG_APPLICATION are not set. Tracing is disabled." 1>&2
            return $OVCSL_ERROR_USAGE
        fi
        
        # Does the XPL tracing CLI binary exist?
        [ -e "$OVCSL_OV_BIN/ovtrcmsg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
        [ -x "$OVCSL_OV_BIN/ovtrcmsg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
        
        typeset trc_msg="$1"
        typeset comp_name="${2:-shell script}"
        typeset attributes="${3:-info}"
        typeset category="${4:-none}"
        
        $OVCSL_OV_BIN/ovtrcmsg "$OVCSL_LOG_APPLICATION" \
                                       "$comp_name" \
                                       "$category" \
                                       "$attributes" \
                                       "$trc_msg"
        return $?
    fi
}

## FUNCTION:    OvCslXplLog
## DESCRIPTION: Log a message using XPL.
##              NOTE: XPL must be installed before this function can be used.
## PARAMETERS:  $OVCSL_LOG_APPLICATION:
##                  Name of the application doing the trace
##              $1: Log message
##              $2: [optional] Component name creating the log entry. Default is
##                  "none"
##              $3: [optional] Severity of the log entry. One of "info", "warn",
##                  "error" or "fatal". Default is "info".
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  XPL logging CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  XPL logging CLI binary is not executable for calling user.
##              Return value of XPL logging CLI binary.
## RETURN ECHO:
## EXAMPLE:     | OvCslXplLog "The filesystem is low on space." \
##              |             "Filesystem Monitor" \
##              |             warn \
##              |             "Output of 'df -t ext3':\n`df -t ext3`"

OvCslXplLog()
{
    # Does the XPL logging CLI binary exist?
    [ -e "$OVCSL_OV_BIN/ovlogmsg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovlogmsg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
    
    typeset log_msg="$1"
    typeset comp_name="${2:-none}"
    case ${3:-info} in
        info)
            typeset sev_param="-i"
            ;;
        warn)
            typeset sev_param="-w"
            ;;
        error)
            typeset sev_param="-e"
            ;;
        fatal)
            typeset sev_param="-f"
            ;;
        *)
            echo "INTERNAL ERROR: Invalid severity  for logging specified. (Function: OvCslXplLog)"
            exit $OVCSL_ERROR_USAGE
            ;;
    esac
    
    $OVCSL_OV_BIN/ovlogmsg $sev_param \
                                   -a "$OVCSL_LOG_APPLICATION" \
                                   -c "$comp_name" \
                                   -msg "$log_msg"
    return $?
}

## FUNCTION:    OvCslXplConfGet
## DESCRIPTION: Read data from XPL config.
## PARAMETERS:  $1: [optional] Namespace. If no namespace and no attribute is
##                  specified, the whole configuration database in config file
##                  syntax is returned.
##              $2: [optional] Attribute. If no attribute is specified all
##                  attributes of the given namespace are returned as multiple
##                  lines in the form
##                  <attribute>=<value>
##              $3: [optional] OV resource group.
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovconfget CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovconfget binary is not executable for calling user.
##              Return value of ovconfget binary. 
## RETURN ECHO: Requested value as described in the parameters section above.

OvCslXplConfGet()
{
    [ -e "$OVCSL_OV_BIN/ovconfget" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovconfget" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
    
    typeset namespace=$1
    typeset attribute=$2    
    if [ -n "$3" ]
    then
        typeset ovrg_param="-ovrg $3"
    else
        typeset ovrg_param=""
    fi  
    
    $OVCSL_OV_BIN/ovconfget $ovrg_param $namespace $attribute
}

## FUNCTION:    OvCslXplConfChange
## DESCRIPTION: Add or change local settings stored in XPL config.
## PARAMETERS:  $1: Namespace.
##              $2: Attribute name.
##              $3: Value of attribute.
##              $4: [optional] OV resource group.
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovconfchg CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovconfchg binary is not executable for calling user.
## RETURN ECHO:

OvCslXplConfChange()
{
    [ -e "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
    
    typeset namespace=$1
    typeset attribute=$2
    typeset value="$3"
    if [ -n "$4" ]
    then
        typeset ovrg_param="-ovrg $4"
    else
        typeset ovrg_param=""
    fi    
    
    $OVCSL_OV_BIN/ovconfchg $ovrg_param -ns $namespace -set $attribute "$value"
}

## FUNCTION:    OvCslGetOVRGDataDir
## DESCRIPTION: Read shared dir From Xpl config.
## PARAMETERS:  $1: Resource group name. 
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovconfget CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovconfget binary is not executable for calling user.
## RETURN ECHO:

OvCslGetOVRGDataDir()
{

   [ -e "$OVCSL_OV_BIN/ovconfget" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
   [ -x "$OVCSL_OV_BIN/ovconfget" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE

 typeset RGName=$1

 Result=`$OVCSL_OV_BIN/ovconfget xpl.dir.shares | grep -w "$RGName" | cut -d '=' -f 2`  
 if [ -d "$Result" ]
  then
    OVRGDataDir=$Result
 fi
 
}

## FUNCTION:    OvCslSetOVRGDataDir
## DESCRIPTION: Set default shared dir in Xpl config.
## PARAMETERS : $1: Resource group name
##              $2: Resource group path
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovconfchg CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovconfchg binary is not executable for calling user.
## RETURN ECHO:

OvCslSetOVRGDataDir()
{
  
  [ -e "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
  [ -x "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE

  typeset RGNAME=$1
  typeset RGPATH=$2
  
  if [ ! -d "$RGPATH" ]
  then
        /bin/mkdir ${RGPATH}
   fi

  $OVCSL_OV_BIN/ovconfchg -namespace xpl.dir.shares -set $RGNAME $RGPATH 
  
 } 

## FUNCTION:    OvCslXplConfTriggerUpdate
## DESCRIPTION: Trigger an update of the XPL configuration database, e.g. after
##              new config files have been added.
##              $1: [optional] OV resource group.
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovconfchg CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovconfchg binary is not executable for calling user.
## RETURN ECHO:

OvCslXplConfTriggerUpdate()
{
    [ -e "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
    
    if [ -n "$1" ]
    then
        typeset ovrg_param="-ovrg $1"
    else
        typeset ovrg_param=""
    fi    
    
    $OVCSL_OV_BIN/ovconfchg $ovrg_param
}

## FUNCTION:    OvCslXplConfClear
## DESCRIPTION: Remove a local setting stored in XPL config.
## PARAMETERS:  $1: Namespace.
##              $2: Attribute name. Set this to * to remove all local settings
##                  in the current namespace.
##              $3: [optional] OV resource group.
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovconfchg CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovconfchg binary is not executable for calling user.
## RETURN ECHO:

OvCslXplConfClear()
{
    [ -e "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovconfchg" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE
    
    typeset namespace=$1
    typeset attribute=$2    
    if [ -n "$3" ]
    then
        typeset ovrg_param="-ovrg $3"
    else
        typeset ovrg_param=""
    fi    
    
    $OVCSL_OV_BIN/ovconfchg $ovrg_param -ns $namespace -clear $attribute
}

## FUNCTION:    OvCslXplGetOvPath
## DESCRIPTION: Retrieving directory names at runtime using ovpath
## PARAMETERS:  Parameters which are accepted by ovpath as defined by Xpl
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovpath CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovpath binary is not executable for calling user.
OvCslXplGetOvPath()
{
  
  [ -e "$OVCSL_OV_BIN/@OVBIN_OVPATH@" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
  [ -x "$OVCSL_OV_BIN/@OVBIN_OVPATH@" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE

  $OVCSL_OV_BIN/@OVBIN_OVPATH@ $* 2>/dev/null

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

## FUNCTION:    OvCslIsOMServerRunning
## DESCRITPION: Checks if the management server processes are running.
##              This checks if the management server database is running.
##              If it is running, agent packages can be registered 
##              and SPIs can be uploaded
## PARAMETERS:  None
## RETURN VAL:  1:  Server processes are running
##              0:  Server processes are not running
## RETURN ECHO: 

OvCslIsOMServerRunning()
{
   if OvCSLIsOMServerInstalled
   then
       ${OVCSL_OV_BIN}/OpC/install/opc_dflt_lang >/dev/null 2>&1
       if [ $? -ne 0 ]
       then
           return 0
       else
           return 1
       fi
   else
       return 1
   fi
}

## FUNCTION:    OvCSLIsOMServerInstalled
## DESCRITPION: Return 0 if HPOM server is installed
## PARAMETERS:  None
## RETURN VAL:  1:  HPOM server is installed
##              0:  HPOM server is not installed
## RETURN ECHO: 
##              

OvCSLIsOMServerInstalled()
{
    if [ ! -x ${OVCSL_OV_BIN}/OpC/opcsw ]
    then
        return 1
    else
        return 0
    fi
}

## FUNCTION:    OvCslConfigureComponent
## DESCRITPION: Configuration script of the Component is invoked
## PARAMETERS:  $1:Name of component to be configured
## RETURN VAL:  0: Success
##              1: Failure
## RETURN ECHO: NONE
##
OvCslConfigureComponent()
{
    typeset componentToConfigure=$1
    configureScript=${OVCSL_OV_LBIN}/configure/${componentToConfigure}/configure.sh
    if [ -x $configureScript -a ! -d $configureScript ]
    then
        OvCslLog $loggedBy "info" "Executing configure script '${configureScript}'"
        ${configureScript} > /dev/null 2>&1
        if [ $? -ne 0 ]
        then
            OvCslLog $loggedBy "error" "Configure script '${configureScript}' failed"
            exit 1
        fi
    else
        OvCslLog $loggedBy "error" "Configure script '${configureScript}' does not exist or does not have execute permissions"
    fi
}

## FUNCTION:    OvCslBackupComponentXml
## DESCRITPION: Copy the Component Xml of Base as base_ComponentNameXml
## PARAMETERS:  $1:Name of component Xml to be backed up
## RETURN VAL:  0: Success
##              1: Failure
## RETURN ECHO: NONE
##
OvCslBackupComponentXml()
{
typeset componentName=$1
typeset srcpath
typeset componentXml
typeset version_base
typeset version_new
typeset check_basexml

componentXml=${componentName}.xml
srcpath=${OVCSL_OV_NEW_CONFIG}/installation/inventory
if [ -f ${srcpath}/${componentXml} ]
then
    check_basexml=`/bin/cat ${srcpath}/${componentXml} | grep "<patch>" 2>/dev/null`
    if [ ! -f ${srcpath}/base_${componentXml} -a "X${check_basexml}" = "X" ]
	then
		/bin/cp -f -f ${srcpath}/${componentXml} ${srcpath}/base_${componentXml} 2> /dev/null
		OvCslLog $loggedBy "info" "Backed up ${componentXml} as ${srcpath}/base_${componentXml}"
	elif [ -f ${srcpath}/base_${componentXml} -a "X${check_basexml}" = "X" ]
    then
        version_base=`/bin/cat ${srcpath}/base_${componentXml} | grep "<version>" | cut -d">" -f2 | cut -d"<" -f1 | /usr/bin/head -1 2>/dev/null`
        version_new=`/bin/cat ${srcpath}/${componentXml} | grep "<version>" | cut -d">" -f2 | cut -d"<" -f1 | /usr/bin/head -1 2>/dev/null`
        if [ `echo ${version_base} | /usr/bin/tr -d '.'`  -ne `echo ${version_new} | /usr/bin/tr -d '.'` ]
        then
            /bin/cp -f -f ${srcpath}/${componentXml} ${srcpath}/base_${componentXml} 2> /dev/null
        fi
	fi
else
    OvCslLog $loggedBy "Error" "Error in backing up base package descriptor ${srcpath}/${componentXml} not found"
	return 1
fi

return 0
}

## FUNCTION:    OvCslCopyComponentXml
## DESCRITPION: Copy the Component patch Xml of componentname-patchnumber and restore base backed up file.
## PARAMETERS:  $1:Name of component Xml to be backed up
## RETURN VAL:  0: Success
##              1: Failure
## RETURN ECHO: NONE
##
OvCslCopyComponentXml()
{
typeset componentName=$1
typeset PATCHNUMBER=$2
typeset srcpath 
typeset componentXml
componentXml=${componentName}.xml
srcpath=${OVCSL_OV_NEW_CONFIG}/installation/inventory

if [ -f ${srcpath}/${componentXml} ]
then
    /bin/cp -f -f ${srcpath}/${componentXml} ${srcpath}/${componentName}-${PATCHNUMBER}.xml 2> /dev/null
	OvCslLog $loggedBy "info" "Copied ${componentXml} from ${srcpath}/${componentXml} to ${srcpath}/${componentName}-${PATCHNUMBER}.xml"
    if [ -f ${srcpath}/base_${componentXml} ]
	then
	    /bin/cp -f -f ${srcpath}/base_${componentXml} ${srcpath}/${componentXml} 2> /dev/null
		OvCslLog $loggedBy "info" "Restored base ${componentXml} from ${srcpath}/base_${componentXml}  to ${srcpath}/${componentXml}"
	fi
else
    OvCslLog $loggedBy "Error" "Error in  Copying component xml ${srcpath}/${componentXml} not found"
	return 1
fi		

return 0
}

## FUNCTION:    OvCslRestoreBaseComponentXml
## DESCRITPION: Restore base backed up file and delete patch related xml.
## PARAMETERS:  $1:Name of component Xml to be backed up
## RETURN VAL:  0: Success
##              1: Failure
## RETURN ECHO: NONE
##
OvCslRestoreBaseComponentXml()
{
typeset componentName=$1
typeset PATCHNUMBER=$2
typeset srcpath
typeset componentXml
componentXml=${componentName}.xml
srcpath=${OVCSL_OV_NEW_CONFIG}/installation/inventory

if [ -f ${srcpath}/${componentXml} ]
then
    if [ -f ${srcpath}/base_${componentXml} ]
	then
		/bin/cp -f -f ${srcpath}/base_${componentXml} ${srcpath}/${componentXml} 2> /dev/null
		OvCslLog $loggedBy "info" "Restored base_${componentXml} from ${srcpath}/base_${componentXml} to ${srcpath}/${componentXml}"
		if [ -f ${srcpath}/${componentName}-${PATCHNUMBER}.xml ]
		then
			/bin/rm -f ${srcpath}/${componentName}-${PATCHNUMBER}.xml 2> /dev/null
			OvCslLog $loggedBy "info" "Deleting patch descriptor file ${srcpath}/${componentName}-${PATCHNUMBER}.xml"
		fi
	fi
fi

return 0

}

## FUNCTION:  OvCslReadINIString  
## DESCRITPION:Read the ini file 
## PARAMETERS:  $1: Section
##              $2: Keyname
##              $3: default value
##              $4: Filename
## RETURN VAL:  0: Success
##              1: Failure
## RETURN ECHO: NONE
##
OvCslReadINIString()
{
    typeset Section=$1
    typeset KeyName="$2="
    typeset DefaultValue=$3
    typeset FileName=$4
    typeset SectionFormated=""
    typeset NextSection=0
    typeset sectionFound=0
    typeset KeyFound=0
    typeset line=""

    if [ ! -f ${FileName} ]
    then
        value=${DefaultValue}
        echo $value
    else
        while read line
        do
           if [ "X$line" = "X${Section}" ]
           then
               sectionFound=1
               continue
           fi
           echo $line | grep '^\[' > /dev/null 2>&1
           if [ $sectionFound -eq 1 -a $? -eq 0 ]
           then
               NextSection=1
           fi
    
           if [ $sectionFound -eq 1 -a  $NextSection -ne 1 ]
           then
               echo $line | grep ${KeyName} > /dev/null 2>&1
               if [ $? -eq 0 ]
               then
                   KeyFound=1
                   value=`echo $line | cut -d"=" -f2`
                   echo $value
                   break
               fi
           fi
    
        done < ${FileName}
    
        if [ $sectionFound -eq 1 -a ${KeyFound} -ne 1 ]
        then
            # Key does not exist. Return default value
            value=${DefaultValue}
            echo $value
        fi
    
        if [ $sectionFound -ne 1 ]
        then
            #Section does not exist
            value=${DefaultValue}
            echo $value
        fi
    fi

    return 0
}

## FUNCTION:  OvCslWriteINIString  
## DESCRITPION:Write to the ini file 
## PARAMETERS:  $1: Section
##              $2: Keyname
##              $3: default value
##              $4: Filename
## RETURN VAL:  0: Success
##              1: Failure
## RETURN ECHO: NONE
##

OvCslWriteINIString()
{
    typeset Section=$1
    typeset KeyName="$2="
    typeset Value=$3
    typeset FileName=$4
    typeset SectionFormated=""
    typeset NextSection=0
    typeset sectionFound=0
    typeset KeyFound=0
    typeset line=""

    SectionFormated=`echo ${Section}| sed s/'\['/'\\\['/ | sed s/'\]'/'\\\]'/`

    while read line
    do
       if [ "X$line" = "X${Section}" ]
       then
           sectionFound=1
           echo $line >> /tmp/tempIni
           continue
       fi

       echo $line | grep '^\[' > /dev/null 2>&1
       if [ $sectionFound -eq 1 -a $? -eq 0 ]
       then
           NextSection=1
       fi

       if [ $sectionFound -eq 1 -a  $NextSection -ne 1 ]
       then
           echo $line | grep ${KeyName} > /dev/null 2>&1
           if [ $? -eq 0 ]
           then
               KeyFound=1
               line="${KeyName}${Value}"
           fi
       fi

       echo $line >> /tmp/tempIni

    done < ${FileName}

       if [ $sectionFound -eq 1 -a ${KeyFound} -ne 1 ]
       then
           # Key does not exist. Add new key
           rm /tmp/tempIni > /dev/null 2>&1
           sed -e '
           /'"${SectionFormated}"'/ a\
'"${KeyName}"''"${Value}"' ' ${FileName} > /tmp/tempIni
       fi

    if [ -s /tmp/tempIni ]
    then
        mv /tmp/tempIni ${FileName}
    fi

    if [ $sectionFound -ne 1 ]
    then
        #Section does not exist. Create new section
        echo "${Section}"  >> ${FileName}
        echo ${KeyName}${Value} >> ${FileName}
    fi

}

## FUNCTION:     OvCslRemoveComponent
## DESCRIPTION:  Updates the component table
## PARAMETERS:   $1: Component ID  (see file header comment for more info)
## RETURN VAL:    0: No error encountered
##               $OVCSL_ERROR_WRITING_FILE: Error writing file
## RETURN ECHO:

OvCslRemoveComponent()
{
    typeset COMPONENT_ID=$1
    typeset SEDSTRING=""
    
    OVCSL_PRODUCT_MATRIX_FILE="${OVCSL_OV_DATA_CONF}/ProductMatrix.cfg"
    OVCSL_COMPONENT_MATRIX_FILE="${OVCSL_OV_DATA_CONF}/ComponentMatrix.cfg"
    OVCSL_DEPENDENCY_MATRIX_FILE="${OVCSL_OV_DATA_CONF}/DependencyMatrix.cfg"

    if [[ ! -d ${OVCSL_OV_DATA_CONF} ]]; then
      return 0
    fi

    COMPONENT_FILE=${OVCSL_COMPONENT_MATRIX_FILE}
    PRODUCT_FILE=${OVCSL_PRODUCT_MATRIX_FILE}
    DEP_FILE=${OVCSL_DEPENDENCY_MATRIX_FILE}

    # DEPRECATED (OvCsl02.00) BEGIN
    # workaround for a bug in previous versions of this library
    if [ -f "$OVCSL_OV_DATA_CONF/product.cfg" ]; then
      /bin/cat "$OVCSL_OV_DATA_CONF/product.cfg" >> $PRODUCT_FILE
      /bin/rm -f "$OVCSL_OV_DATA_CONF/product.cfg"
    fi
    # DEPRECATED (OvCsl02.00) END

    # delete all lines with the current component (should only be one), write result to tmp file
    if [[ -f ${COMPONENT_FILE} ]]; then
      SEDSTRING='/^'${COMPONENT_ID}'/d'
      sed -e ${SEDSTRING} ${COMPONENT_FILE} > ${COMPONENT_FILE}.tmp

      if ! /bin/mv ${COMPONENT_FILE}.tmp ${COMPONENT_FILE}; then
        return $OVCSL_ERROR_WRITING_FILE
      fi

      # remove component matrix if it is empty
      if [[ ! -s ${COMPONENT_FILE} ]]; then
        /bin/rm -f ${COMPONENT_FILE}
      fi
    fi
    # delete all lines with the current component in the product file (should only be one), write result to tmp file
    if [[ -f ${PRODUCT_FILE} ]]; then
      typeset wspaces=`echo -e " \t\v"`
      SEDSTRING="/[$wspaces]${COMPONENT_ID}[$wspaces]/d"
      sed -e "${SEDSTRING}" ${PRODUCT_FILE} > ${PRODUCT_FILE}.tmp

      if ! /bin/mv ${PRODUCT_FILE}.tmp ${PRODUCT_FILE}; then
        return $OVCSL_ERROR_WRITING_FILE
      fi
    fi

    # delete all lines with the current component in the dependecy file write result to tmp file
    if [[ -f ${DEP_FILE} ]]; then
      SEDSTRING='/^'${COMPONENT_ID}'/d'
      sed -e ${SEDSTRING} ${DEP_FILE} > ${DEP_FILE}.tmp

      if ! /bin/mv ${DEP_FILE}.tmp ${DEP_FILE}; then
        return $OVCSL_ERROR_WRITING_FILE
      fi

      # remove DependencyMatrix if empty
      if [[ ! -s ${DEP_FILE} ]]; then
        /bin/rm -f ${DEP_FILE}
      fi
    fi

    return 0
}

## FUNCTION:    OvCslXplConfGetFromFile
## DESCRIPTION: Read data from XPL config.
## PARAMETERS:  $1: Namespace.
##              $2: Attribute.
##              $3: Configuration file full path.
## RETURN VAL:  $OVCSL_ERROR_FILE_NOT_FOUND:
##                  ovconfget CLI binary cannot be found.
##              $OVCSL_ERROR_FILE_NOT_EXECUTABLE:
##                  ovconfget binary is not executable for calling user.
##              Return value of ovconfget binary.
## RETURN ECHO: Requested value as described in the parameters section above.
OvCslXplConfGetFromFile()
{
    [ -e "$OVCSL_OV_BIN/ovconfget" ] || return $OVCSL_ERROR_FILE_NOT_FOUND
    [ -x "$OVCSL_OV_BIN/ovconfget" ] || return $OVCSL_ERROR_FILE_NOT_EXECUTABLE

    typeset filepath=$1
    typeset namespace=$2
    typeset attribute=$3

    $OVCSL_OV_BIN/ovconfget -file ${filepath} $namespace $attribute
}

## FUNCTION:    OvCslIsComponentConfigured
## DESCRIPTION: Check if the component has been configured after installation.
##              This is done by checking the presence of package descriptor XML file
##              in the ${OVCSL_OV_DATA}/installation/inventory/ directory.
## PARAMETERS:  Component name like HPOvXpl etc.
## RETURN VAL:  0 : if component is configured
##              1 : if component is not configured
OvCslIsComponentConfigured()
{

  typeset compname=$1
  typeset invfile="${OVCSL_OV_DATA}/installation/inventory/${compname}.xml"

  if [ -e "${invfile}" ]
  then
     return 0
  else
     return 1
  fi
}

## FUNCTION:    OvCslUnConfigureComponent
## DESCRITPION: Configuration script of the Component is invoked with -u option ## PARAMETERS:  $1:Name of component to be Unconfigured ## RETURN VAL:  0: Success
##              1: Failure
## RETURN ECHO: NONE
##

OvCslUnConfigureComponent()
{
    typeset componentToUnConfigure=$1
    configureScript=${OVCSL_OV_LBIN}/configure/${componentToUnConfigure}/configure.sh
    if [ -x $configureScript ] && [ ! -d $configureScript ]; then
        OvCslLog $loggedBy "info" "Executing configure script '${configureScript}' for unconfigure"
        ${configureScript} -u > /dev/null 2>&1
        if [ $? -ne 0 ]
        then
            OvCslLog $loggedBy "error" "Configure script '${configureScript}' failed for unconfigure"
            exit 1
        fi
    else
        OvCslLog $loggedBy "error" "Configure script '${configureScript}' does not exist or does not have execute permissions "
    fi
}

## FUNCTION:    OvCslLinuxBitsCheck
## DESCRITPION: Check for the architecture type only for Linux systems
## PARAMETERS:  None
## RETURN VAL:  0: If not version 4 or 9 respectively
##              1: success version check
## RETURN ECHO: NONE
##

OvCslLinuxBitsCheck ()

{

   typeset VERSION
   typeset ret=0

    if [ -f /etc/redhat-release ]
    then
        # For RHEL 4 x64/ia64 we support 32 bit agent
        VERSION=`cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*// \
        | cut -d. -f1`
        if [ $VERSION -eq 4 ]
        then
            ret=1
        fi

    elif [ -f /etc/SuSE-release ]
    then
        # For SLES 9 x64/ia64 we support 32 bit agent
        VERSION=`cat /etc/SuSE-release | grep 'VERSION *= *' | cut -d= -f2 | sed "s/ //"`
        if [ $VERSION -eq 9 ]
        then
            ret=1
        fi
    fi

    return ${ret}
}

## FUNCTION:    OvCslCheckArchitecture
## DESCRITPION: Check for the processor architecture type and compare to the parameter 
##              passed to the function
## PARAMETERS:  $1 Reference processor architecture passed to the function
## RETURN VAL:  0: Success
##              1: Faliure
## RETURN ECHO: NONE
##

OvCslCheckArchitecture ()
{

typeset processorType_ref=$1
typeset managedNodeType
typeset retval=0
typeset processorType

if [ "X${processorType_ref}" != "X" ]
then
    if [ "X${processorType_ref}" = "XLinux2.6" ]
    then
        processorType="x86"
    elif [ "X${processorType_ref}" = "XLinux2.6_64" ]
    then
        processorType="x64"
    elif [ "X${processorType_ref}" = "XLinux2.6_IPF64" ]
    then
        processorType="IPF64"
    elif [ "X${processorType_ref}" = "XLinux2.6_PPC64" ]
    then
        processorType="ppc64"
    else
        processorType=""
   fi
fi

typeset machineType
machineType=`uname -m 2> /dev/null`
if [ $? -eq 0 ]
then
        case ${machineType} in
            x86_64)
                OvCslLinuxBitsCheck
                if [ $? -eq 1 ]
                then
                    managedNodeType="x86"
                    OvCslLog $loggedBy "info" "Determined node architecture: ${managedNodeType}"
                else
                    managedNodeType="x64"
                    OvCslLog $loggedBy "info" "Determined node architecture: ${managedNodeType}"
                fi
            ;;
            ia64)
                OvCslLinuxBitsCheck
                if [ $? -eq 1 ]
                then
                    managedNodeType="x86"
                    OvCslLog $loggedBy "info" "Determined node architecture: ${managedNodeType}"
                else
                    managedNodeType="IPF64"
                    OvCslLog $loggedBy "info" "Determined node architecture: ${managedNodeType}"
                fi
            ;;

           ppc64)
                    managedNodeType="ppc64"
                    OvCslLog $loggedBy "info" "Determined node architecture: ${managedNodeType}"
            ;;
            *)
                managedNodeType="x86"
                OvCslLog $loggedBy "info" "Determined node architecture: ${managedNodeType}"
            ;;
        esac
else
        retval=`expr ${retval} + 1`
        OvCslLog $loggedBy "error" "Unable to determine the Linux node architecture"
fi

if [ ${retval} -eq 0 ]
then
    if [ "X${processorType}" != "X" ] 
    then 
       if [ "X${managedNodeType}" = "X${processorType}" ]
       then
           OvCslLog $loggedBy "info"  "Determined that the package architecture and node architecture are compatible: ${managedNodeType}"
       else
           OvCslLog $loggedBy "error"  "Packages are of type: ${processorType} whereas the node is of type: ${managedNodeType}"
           retval=`expr ${retval} + 1`
       fi
    else
       retval=`expr ${retval} + 1`
       OvCslLog $loggedBy "error"  "Determined processor acrhitecture is not supported"
    fi
fi

return ${retval}

}

## FUNCTION:    OvCslRemoveComponentHotfix
## DESCRITPION: Removal of hotfix files for patch upgrade
## PARAMETERS:  2 parameters 1: component name and 2: backup location
## RETURN VAL:  NONE
## RETURN ECHO: NONE
## 
OvCslRemoveComponentHotfix()
{
  typeset componentName=$1
  typeset backupDirectory=$2
  typeset versionInstalled=""
  typeset componentXml=""
  typeset xmlsToRemove=""
  typeset filename=""
  typeset version=""
  typeset ishotfix=""

  componentXml=${OVCSL_OV_NEW_CONFIG}/installation/inventory/${componentName}.xml
  versionInstalled=`/bin/cat ${componentXml}| grep "<version>" | cut -d">" -f2 | cut -d"<" -f1 | /usr/bin/head -1 2>/dev/null`

  xmlsToRemove=`ls ${OVCSL_OV_DATA}/installation/inventory/${componentName}-* 2>/dev/null`
  for filename in ${xmlsToRemove}
  do
    version=`/bin/cat ${filename} | grep "<version>" | cut -d">" -f2 | cut -d"<" -f1 | /usr/bin/head -1 2>/dev/null`
    ishotfix=`/bin/cat ${filename} | grep "<ishotfix>" | cut -d">" -f2 | cut -d"<" -f1 | /usr/bin/head -1 2>/dev/null`
    if [ "X${ishotfix}" = "Xtrue" ]
    then
        if [ `echo ${version} | /usr/bin/tr -d '.'`  -lt `echo ${versionInstalled} | /usr/bin/tr -d '.'` ]
        then
        #remove the XML
            OvCslLog $loggedBy "info" "Removing the Hotfix file ${filename}"
            /bin/rm -f ${filename}

            pkgname=`echo ${filename} | awk -F/ '{ print $NF }' | cut -d "." -f1`
                
        #remove Hotfix backup
	        if [ "X${pkgname}" != "X" ]
	        then
                if [ -d ${backupDirectory}/${pkgname} ]
                then
		            OvCslLog $loggedBy "info" "Removing the Hotfix backup directory ${pkgname} from the ${backupDirectory}"
                    /bin/rm -f -r ${backupDirectory}/${pkgname}
	            else
		            OvCslLog $loggedBy "info" "The Hotfix backup directory ${pkgname} was not found in ${backupDirectory}"
                fi
	        fi
        fi
    else
	     OvCslLog $loggedBy "info" "The Patch xml found ${filename}"
    fi
 
  done
}

##FUNCTION:      OvCslStartXPLTraceService
## DESCRPTION:   Registers and starts the Trace Server.
## PARAMETERS:   - none -
## RETURN VAL:   0: Success
##               1: Failure

OvCslStartXPLTraceService()
{

# add Trace Server to system startup procedure
init_script=`OvCslMakeInitScript "OVTrcSrv" \
        "(umask 002; ${OVCSL_OV_LBIN}/xpl/trc/ovtrcd)" \
        "${OVCSL_OV_SUPPORT}/ovtrcadm -srvshutdown > /dev/null 2>&1"`

OvCslAddInitScript $init_script \
                        "$OVCSL_RC_WITH_NETWORK" \
                        90 \
                        02
RET=$?
    if [ $RET -ne 0 -a $RET -ne 5 -a $RET -ne 6 ]; then
        OvCslStrMsgFmt 5 "Unable to add init script OVTrcSrv, error code: $RET" 2>&1
        exit 1
    fi

# We do not need the generated script anymore
/bin/rm -f $init_script

   if ! OvCslControlInitScript OVTrcSrv start
   then
       OvCslStrMsgFmt 5  "Unable to start XPL TraceServer daemon" 2>&1
       exit 1
   fi
}
##FUNCTION:      OvCslStopXPLTraceService
## DESCRPTION:   Stops and Removes the Trace Server.
## PARAMETERS:   - none -
## RETURN VAL:   0: Success
##               1: Failure

OvCslStopXPLTraceService()
{
IS_IT_SHARED_WPAR=$FALSE

	ps -ef | grep ovtrcd | grep -v grep >/dev/null 2>&1

RETURN_CODE=$?

   if [ $RETURN_CODE -eq 0 ] ; then
      if ! OvCslControlInitScript OVTrcSrv stop
      then
         OvCslStrMsgFmt 5 "Unable to stop XPL TraceServer daemon" 2>&1
      exit 1
      fi
   fi

# remove TraceServer script from system startup
OvCslRemoveInitScript OVTrcSrv 90 02
}

## FUNCTION:    OvCslRemovePatchInventoryFilesFromNewConfig
## DESCRIPTION: Removes the patch and hotfix inventory xml and 
##              component xml files backed up with base_ prefix 
##              from the Installdir/newconfig inventory location.
## PARAMETERS:  Component Name
## RETURN VAL:  0 : File removal success
## RETURN ECHO: Filtered string without empty lines.

OvCslRemovePatchInventoryFilesFromNewConfig()
{
  Component_name=$1

  inv_xml_files=`ls ${OVCSL_OV_NEW_CONFIG}/installation/inventory/*${Component_name}*.xml 2>/dev/null`

  if [ "x${inv_xml_files}" != "x" ]
  then
     for comp_patch_name in ${inv_xml_files}
     do
       grep "<patchid>" ${comp_patch_name} > /dev/null 2>&1
       flag1=$?
       echo $comp_patch_name | grep base_ > /dev/null 2>&1
       flag2=$?
       if [ $flag1 -eq 0 -o $flag2 -eq 0 ]
       then
           OvCslLog $loggedBy "info" "Removing the inventory xml:${comp_patch_name}"
           /bin/rm -f ${comp_patch_name}
           if [ $? -ne 0 ]
           then
               OvCslLog $loggedBy "warning" "Removal of the inventory xml:${comp_patch_name} failed"
           fi
       fi
     done
  fi

  return 0

}

## FUNCTION:    OvCslRemovePatchInventoryFiles
## DESCRIPTION: Removes the patch and hotfix inventory xml files
##              from the Datadir inventory location
## PARAMETERS:  Component Name
## RETURN VAL:  0 : File removal success
##              1 : File removal failure
## RETURN ECHO: Filtered string without empty lines.

OvCslRemovePatchInventoryFiles()
{
  Component_name=$1

  inv_xml_files=`ls ${OVCSL_OV_DATA}/installation/inventory/${Component_name}*.xml 2>/dev/null`
  if [ "x${inv_xml_files}" != "x" ]
  then
     for comp_patch_name in ${inv_xml_files}
     do
       grep "<patchid>" ${comp_patch_name} > /dev/null 2>&1
       if [ $? -eq 0 ]
       then
          OvCslLog $loggedBy "info" "Removing the inventory xml:${comp_patch_name}"
          /bin/rm -f ${comp_patch_name}
          if [ $? -ne 0 ]
          then
             return 1
          fi
       fi
     done
  fi

  return 0

}

## FUNCTION:    OvCslRemoveLCPackages
## DESCRIPTION: Removes all the Lcore catalog packages if exists
## PARAMETERS:  - None -
## RETURN VAL: 0 - Success 
##             1 - Failure 
## RETURN ECHO: Success or Failure message

OvCslRemoveLCPackages()
{

declare -a LC_CATALOG_PACKAGES; LC_CATALOG_PACKAGES=(HPOvLcde HPOvLces HPOvLcfr HPOvLcja HPOvLcko HPOvLcnl HPOvLcpB HPOvLcru HPOvLczC HPOvEaAes HPOvEaAja HPOvEaAko HPOvEaAzC)

LC_LIST_COMMAND="rpm -qa"
LC_PACKAGE_REMOVE_COMMAND="rpm -e --nodeps"

LC_PACKAGE_LIST_FILE="/tmp/getlcpkglist.out"

if [ -f ${LC_PACKAGE_LIST_FILE} ]
then
   rm -f ${LC_PACKAGE_LIST_FILE}
fi

${LC_LIST_COMMAND} > ${LC_PACKAGE_LIST_FILE} 2>/dev/null

    typeset i=0

    while [ $i -lt ${#LC_CATALOG_PACKAGES[*]} ]
    do
       grep ${LC_CATALOG_PACKAGES[i]} ${LC_PACKAGE_LIST_FILE} >/dev/null 2>&1
       if [ $? -eq 0 ]
       then
           ${LC_PACKAGE_REMOVE_COMMAND} ${LC_CATALOG_PACKAGES[i]} >/dev/null 2>&1
           if [ $? -eq 0 ]
           then
               OvCslStrMsgFmt 2 "Successfully removed the component package ${LC_CATALOG_PACKAGES[i]}" 2>&1
           else
               OvCslStrMsgFmt 5 "Fail to remove the component package ${LC_CATALOG_PACKAGES[i]}" 2>&1
           return 1
           fi
      else
          OvCslStrMsgFmt 2 "The component package ${LC_CATALOG_PACKAGES[i]} not found in the database" 2>&1
      fi
      i=`expr $i + 1`
   done

   return 0

}

## FUNCTION:    OvCslGetErrorMsg
## DESCRIPTION: Echos the error message of a given error code (see the
##              OVCSL_ERROR_* constants)
## PARAMETERS:  $1: Error code
## RETURN VAL:  0:  Success
##              1:  The specified error code can not be found in the predefined
##                  error message catalog.
## RETURN ECHO: Raw error message (use OvCslEcho to format it).

OvCslGetErrorMsg()
{
    if [ -z "${OVCSL_ERROR_MESSAGES[$1]}" ]; then
        return 1
    else
        echo "${OVCSL_ERROR_MESSAGES[$1]}"
        return 0
    fi
}

## FUNCTION:    OvCslGetOptionsTable
## DESCRIPTION: Parse the specified options from a arguments list and echo the
##              option in a list that can be parsed e.g. by OvCslGetOptionValue.
##              The options can be abbreviated by putting a colon between the
##              abbreviation and the rest of the option name.
##              In the argument list, options must start with a minus and data
##              with no minus. If a option does not have data the last field in
##              the returned option table will be the value of $TRUE (0).
## PARAMETERS:  $1: List of parameters to parse. Separate the short part from
##                  the long part with a colon.
##              $2: The arguments passed to the script/function that calls this
##                  function ($*)
## RETURN VAL:  0:  Success
##              1:  $2 contains parameters that are not listed in $1
##              2:  Parse error
## RETURN ECHO: Parsable option table for use with OvCslGetOptionValue
## EXAMPLE:     To get the options list from a script that has been called like:
##              | script.sh -in foo.txt -output /tmp/out.txt
##              you could call this function in script.sh as below:
##              | OvCslGetOptionsTable "in:put out:put version" "$*"
OvCslGetOptionsTable()
{
    typeset options="$1"
    typeset arguments="$2"
    typeset unknown_option=$FALSE
    typeset options_list="`echo "$options" | sed 's/:[^ ]*//g'` `echo "$options" | sed 's/://g'`"
    typeset option
    typeset value
    typeset parameter

    # eval command to set also arguments with spaces surrounded by quotation marks
    eval "set -- $arguments"

    while [ $# -gt 0 ]; do
        if echo "$1" | grep ^- >/dev/null; then
            option=`echo "$1" | sed 's/^-//'`
            if echo " $options_list " | grep " $option " >/dev/null; then
                shift
                # is the next argument a option's value?
                if ! echo "$1" | grep ^- >/dev/null; then
                    value=$1
                    shift
                else
                    value=$TRUE
                fi
                # if specified option is a short version, get the long name
                if echo " $options " | grep " $option:" >/dev/null; then
                    option=`echo " $options " | sed "s/.* ${option}:\([^ ]*\) .*/${option}\1/"`
                fi
                echo "${option}:${value}"
            else
                unknown_option=$TRUE
                shift
                if ! echo "$1" | grep ^- >/dev/null; then
                    shift
                fi
            fi
        else
            return 2
        fi
    done

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

## FUNCTION:    OvCslGetOptionValue
## DESCRIPTION: Return the value of the given option from a option table.
## PARAMETERS:  $1: Option table (see OvCslGetOptionsTable)
##              $2: The long name of the option, which value should be returned.
##                  The long name may contain a colon (as specified in the
##                  first parameter of OvCslGetOptionsTable).
## RETURN VAL:  0:  Success / Value found in option table
##              1:  Value not found in option table
## RETURN ECHO: Option Value
## EXAMPLE:     | opttab=`OvCslGetOptionsTable "in:put out:put version" "$*"`
##              | if OvCslGetOptionValue "$opttab" version >/dev/null; then
##              |     echo "`basename $0`: Version 0.0.1"
##              |     exit 0
##              | fi
##              | out_file=`OvCslGetOptionValue "$opttab" output`

OvCslGetOptionValue()
{
    typeset opt_tab="$1"
    typeset option=`echo $2 | sed s/://g`

    if ! echo "$opt_tab" | grep "^${option}:" >/dev/null; then
        # Specified option does not exist in option table
        return 1
    fi

    echo "$opt_tab" | grep "^${option}:" | sed "s/^${option}:\(.*\)$/\1/"
    return 0
}

## FUNCTION:    OvCslTrace
## DESCRIPTION: Trace a message if tracing is enabled via the environment
##              variables $OVCSL_TRACE and $OVCSL_TRACE_FILE.
##              The function OvCslLog will also call this function to ensure
##              that all log messages are also sent to the trace log. So don't
##              call OvCslLog and OvCslTrace for the same message.
##              NOTE: This function may only be used as long as XPL is not
##              installed on the system. After XPL has been installed use
##              the function OvCslXplTrace from OvCslOpenView.shi instead.
## PARAMETERS:  $OVCSL_TRACE:
##                  Anything else than an empty string (e.g. OVCSL_TRACE=1):
##                          Tracing enabled
##                  "" or not set:
##                          Tracing disabled 
##              $OVCSL_TRACE_FILE:
##                  File to which append the trace message
##              $OVCSL_LOG_APPLICATION:
##                  Name of the application doing the trace
##              $1: Component name doing the trace.
##              $2: Trace message.
## RETURN VAL:  0:
##              1:  Unable to write to trace file.
## RETURN ECHO:

OvCslTrace()
{
    if [ ! -z "$OVCSL_TRACE" ]; then
        if [ -z "$OVCSL_TRACE_FILE" -o -z "$OVCSL_LOG_APPLICATION" ]; then
            echo "INTERNAL ERROR: Trace variables OVCSL_TRACE, OVCSL_TRACE_FILE and OVCSL_LOG_APPLICATION are not set. Tracing is disabled." 1>&2
            return $OVCSL_ERROR_USAGE
        fi
        if [ ! -f "$OVCSL_TRACE_FILE" ]; then
            typeset trc_file="`basename $OVCSL_TRACE_FILE`"
            typeset trc_dir="`echo $OVCSL_TRACE_FILE | sed s/\\\\/$trc_file$//`"
            if ! /bin/mkdir -p $trc_dir; then
                return 1
            fi
            if ! touch $OVCSL_TRACE_FILE; then
                return 1
            fi
        fi

        OvCslRotateLog $OVCSL_TRACE_FILE $OVCSL_TRACE_FILE_SIZE

        if [ ! -w $OVCSL_TRACE_FILE ]; then
            return 1
        else
            echo "[`date +'%x %T'`] [$OVCSL_LOG_APPLICATION] [$1] $2" >> $OVCSL_TRACE_FILE
        fi
    fi
}

## FUNCTION:    OvCslLog
## DESCRIPTION: Log a message. The message will be appended to the file given by
##              the environment variable OVCSL_LOG_FILE
##              NOTE: This function may only be used as long as XPL is not
##              installed on the system. After XPL has been installed use
##              the function OvCslXplLog from OvCslOpenView.shi instead.
##              Currently OvCslXplLog is a wrapper that calls this function
##              since a XPL command line logging tool is not yet available.
## PARAMETERS:  $OVCSL_LOG_FILE:
##                  File to which append the log message
##              $OVCSL_LOG_APPLICATION:
##                  Name of the application doing the log
##              $1: Component name doing the log.
##              $2: Severity: One of "info", "warn" or "error"
##              $3: Log message.
## RETURN VAL:  0:  OK
##              1:  Unable to write to log file.
## RETURN ECHO:

OvCslLog()
{

    msg_severity=$2
    
    if [ $msg_severity = "info" -o $msg_severity = "Info" ]
    then
           msg_severity=INFO
    fi
    
    if [ $msg_severity = "warning" -o $msg_severity = "Warning" ]
    then
           msg_severity=WARNING
    fi
    
    if [ $msg_severity = "error" -o $msg_severity = "Error" ]
    then
           msg_severity=ERROR
    fi

    if [ -z "$OVCSL_LOG_APPLICATION" ]; then
        echo "INTERNAL ERROR: Log variable OVCSL_LOG_APPLICATION is not set. Logging is disabled." 1>&2
        return $OVCSL_ERROR_USAGE
    fi

    if [ ! -f "$OVCSL_LOG_FILE" ]; then
        typeset log_file="`basename $OVCSL_LOG_FILE`"
        typeset log_dir="`echo $OVCSL_LOG_FILE | sed s/\\\\/$log_file$//`"
        if ! /bin/mkdir -p $log_dir; then
            OvCslTrace "OvCslLog" "Trace log $OVCSL_LOG_FILE is not writeable"
            return 1
        fi
        if ! touch $OVCSL_LOG_FILE; then
            OvCslTrace "OvCslLog" "Trace log $OVCSL_LOG_FILE is not writeable"
            return 1
        fi
    fi

    OvCslRotateLog $OVCSL_LOG_FILE $OVCSL_LOG_FILE_SIZE

    if [ ! -w $OVCSL_LOG_FILE ]; then
        OvCslTrace "OvCslLog" "Trace log $OVCSL_LOG_FILE is not writeable"
        return 1
    else
        if [ ! -z "$1" ]; then
          echo "[`date +'%x %T'`] [$OVCSL_LOG_APPLICATION] [$1] [$msg_severity] $3" >> $OVCSL_LOG_FILE
        else
          echo "[`date +'%x %T'`] [$OVCSL_LOG_APPLICATION] [$msg_severity] $3" >> $OVCSL_LOG_FILE
        fi
        OvCslTrace "OvCslLog" "Log: $msg_severity: $3"
    fi
}

## FUNCTION:    OvCslCmpVersions
## DESCRIPTION: Compares two version numbers. Valid version numbers are numbers
##              separated by one of the following charakters: .-#/
## PARAMETERS:  $1: Version number 1
##              $2: Version number 2
## RETURN VAL:  0:  success
##              1:  $1 contains invalid characters.
##              2:  $2 contains invalid characters.
## RETURN ECHO: =:  $1 and $2 are equal
##              >:  $1 is greater than $2
##              <:  $1 is less than $2

OvCslCmpVersions()
{
    typeset ver1_str="`echo "$1" | tr '.\\#/-' '    '`"
    typeset ver2_str="`echo "$2" | tr '.\\#/-' '    '`"
    typeset ver1=0
    typeset ver2=0
    typeset result=0
    typeset field=0
    
    echo "$ver1_str" |  grep '^[0-9 ]*$' > /dev/null || return 1
    echo "$ver2_str" |  grep '^[0-9 ]*$' > /dev/null || return 2
    
    while [ $result = 0 ]; do
        field=`/usr/bin/expr $field + 1`
        ver1=`echo $ver1_str | cut -d " " -f $field`
        ver2=`echo $ver2_str | cut -d " " -f $field`
        
        if [ -z "$ver1" -a -z "$ver2" ]; then
            result="="
        elif [ -z "$ver1" -a -n "$ver2" ]; then
            result="<"
        elif [ -n "$ver1" -a -z "$ver2" ]; then
            result=">"
        elif [ "$ver1" -gt "$ver2" ]; then
            result=">"
        elif [ "$ver1" -lt "$ver2" ]; then
            result="<"
        fi
    done
    echo $result
    return 0
}

# Set bash built-in echo command to interpret special (backslash) characters.
shopt -s xpg_echo

# Constants
OVCSL_INSTALL_DATE=`date +%y-%m-%d`
OVCSL_PRODUCT_MATRIX_FILE="${OVCSL_OV_DATA_CONF}/ProductMatrix.cfg"
OVCSL_COMPONENT_MATRIX_FILE="${OVCSL_OV_DATA_CONF}/ComponentMatrix.cfg"
OVCSL_DEPENDENCY_MATRIX_FILE="${OVCSL_OV_DATA_CONF}/DependencyMatrix.cfg"

## FUNCTION:     OvCslWriteProductContents
## DESCRIPTION:  Every product needs to add their components to the
##               compatibility matrix. This function opens the file and
##               adds the specified information.
## PARAMETERS:   $1: Product ID (see file header comment for more info)
##               $2: Product Version
##               $3: Component ID (see file header comment for more info)
##               $4: Component Version
## RETURN VAL:   0:  File updated correctly
##               $OVCSL_ERROR_WRITING_FILE:  Error updating file
##               2:  Component not installed according to component file entries found
## RETURN ECHO:  

OvCslWriteProductContents()
{
  # parse first two parameter and set respective variables
  PRODUCT_FILE=${OVCSL_PRODUCT_MATRIX_FILE}
  COMPONENT_FILE=${OVCSL_COMPONENT_MATRIX_FILE}
  PRODUCT_ID=$1
  PRODUCT_VERSION=$2
  COMPONENT_ID=$3
  COMPONENT_VERSION=$4
  
  # DEPRECATED (OvCsl02.00) BEGIN
  # workaround for a bug in previous versions of this library
  if [ -f "$OVCSL_OV_DATA_CONF/product.cfg" ]; then
    /bin/cat "$OVCSL_OV_DATA_CONF/product.cfg" >> $PRODUCT_FILE
    /bin/rm -f "$OVCSL_OV_DATA_CONF/product.cfg"
  fi
  # DEPRECATED (OvCsl02.00) END

  if ! grep -e "${COMPONENT_ID}[[:space:]]\{1,\}" ${COMPONENT_FILE} | grep ${COMPONENT_VERSION} > /dev/null 2>&1; then
    return 2
  fi

    #
    # Check whether Product matrix file exist
    # If not create it
    #
  
  if [[ ! -f ${PRODUCT_FILE} ]]; then    
        
    # create conf directory if not already present
    if [[ ! -d ${OVCSL_OV_DATA_CONF} ]]; then
        /bin/mkdir -p -m 775 ${OVCSL_OV_DATA_CONF}
    fi   
    touch ${PRODUCT_FILE}      
  fi

  if [ -n ""`grep -e "${PRODUCT_ID}[[:space:]]\{1,\}" ${PRODUCT_FILE}` ]; then
    OLD_VERSION=`grep -e "${PRODUCT_ID}[[:space:]]\{1,\}" ${PRODUCT_FILE} | awk '{ print $2 }' | head -1`
    if [[ ${OLD_VERSION} -ge ${PRODUCT_VERSION} ]]; then
      echo "Warning: Higher or same version of "${PRODUCT_ID}" already appears in product file: "${OLD_VERSION}" vs. "${PRODUCT_VERSION}"."
    else
      SEDSTRING='/^'${PRODUCT_ID}'/d'
      sed -e ${SEDSTRING} ${PRODUCT_FILE} > ${PRODUCT_FILE}.tmp
      if ! /bin/mv ${PRODUCT_FILE}.tmp ${PRODUCT_FILE}; then
        return $OVCSL_ERROR_WRITING_FILE
      fi
    fi
  fi

  if ! echo ${PRODUCT_ID}"	"${PRODUCT_VERSION}"	"${COMPONENT_ID}"	"${CURRENT_VERSION}"	"${OVCSL_INSTALL_DATE} >> ${PRODUCT_FILE}; then
    return $OVCSL_ERROR_WRITING_FILE
  fi

  # sort the file according to the Product names
  /bin/cat ${PRODUCT_FILE} | sort > ${PRODUCT_FILE}.tmp
  if ! /bin/mv ${PRODUCT_FILE}.tmp ${PRODUCT_FILE}; then
    return $OVCSL_ERROR_WRITING_FILE
  fi

return 0
}

## FUNCTION:     OvCslRemoveProductContents
## DESCRIPTION:  Updates the product version table after deletion of a product
## PARAMETERS:   $1: Product ID
##               $2: version that is deleted
## RETURN VAL:    0: No error encountered
##               $OVCSL_ERROR_WRITING_FILE: Error writing file
## RETURN ECHO:  

OvCslRemoveProductContents()
{
  PRODUCT_ID=$1
  PRODUCT_VER=$2

  if [[ ! -d ${OVCSL_OV_DATA_CONF} ]]; then
    return 0
  fi
    
  PRODUCT_FILE=${OVCSL_PRODUCT_MATRIX_FILE}
  
  # DEPRECATED (OvCsl02.00) BEGIN
  # workaround for a bug in previous versions of this library
  if [ -f "$OVCSL_OV_DATA_CONF/product.cfg" ]; then
    /bin/cat "$OVCSL_OV_DATA_CONF/product.cfg" >> $PRODUCT_FILE
    /bin/rm -f "$OVCSL_OV_DATA_CONF/product.cfg"
  fi
  # DEPRECATED (OvCsl02.00) END
  
  # delete all lines with the current component (should only be one), write result to tmp file
  SEDSTRING='/^'${PRODUCT_ID}.${PRODUCT_VER}'/d'
  sed -e ${SEDSTRING} ${PRODUCT_FILE} > ${PRODUCT_FILE}.tmp

  if ! /bin/mv ${PRODUCT_FILE}.tmp ${PRODUCT_FILE}; then
    return $OVCSL_ERROR_WRITING_FILE
  fi

  # remove component matrix if it is empty
  if [[ ! -s ${PRODUCT_FILE} ]]; then
    /bin/rm -f ${PRODUCT_FILE}
  fi
}

## FUNCTION:     OvCslComponentConflict
## DESCRIPTION:  Checks whether a given component should be installed
## PARAMETERS:   $1: Component ID  (see file header comment for more info)
##               $2: current version of component
##               $3: lowest compatible version
## RETURN VAL:    0: No component conflict found, component may be safely installed
##                1: Component version too high, another product requires a lower version
##               -1: Component version too low
## RETURN ECHO:  

OvCslComponentConflict()
{

  COMPONENT_ID=$1
  SUPP_VER=$3
  CURRENT_VERSION=$2
  LOWEST_SUPPORTED=$3

  PRODUCT_FILE=${OVCSL_PRODUCT_MATRIX_FILE}
  COMPONENT_FILE=${OVCSL_COMPONENT_MATRIX_FILE}
  
  # DEPRECATED (OvCsl02.00) BEGIN
  # workaround for a bug in previous versions of this library
  if [ -f "$OVCSL_OV_DATA_CONF/product.cfg" ]; then
    cat "$OVCSL_OV_DATA_CONF/product.cfg" >> $PRODUCT_FILE
    rm "$OVCSL_OV_DATA_CONF/product.cfg"
  fi
  # DEPRECATED (OvCsl02.00) END

  if [[ ! -a ${PRODUCT_FILE} && ! -a ${COMPONENT_FILE} ]]; then
    return 0
  fi

  # get all required versions of the current component
  if [[ -a ${COMPONENT_FILE} ]]; then
    COMPONENT_VERSIONS=`grep -e "${COMPONENT_ID}[[:space:]]\{1,\}" ${COMPONENT_FILE} | awk '{ print $2 }'`
  fi
  SUPPORTED_VERSIONS=`echo \`grep -e "${COMPONENT_ID}[[:space:]]\{1,\}" ${COMPONENT_FILE} | awk '{ print $3 }'\``

  if [ x = x"${COMPONENT_VERSIONS}" -a y = y"${SUPPORTED_VERSIONS}" ]; then
    return 0
  fi

  if [ x = x"${COMPONENT_VERSIONS}" ]; then
    COMPONENT_VERSIONS=`echo ${CURRENT_VERSION}`
  fi

  # determine minimal required version
  typeset RE="="
  COMPONENT_MIN="999.0"
  for i in ${COMPONENT_VERSIONS}; do
    COMPONENT_VERSION=`echo ${i}`
    RE=`OvCslCmpVersions ${COMPONENT_VERSION} ${COMPONENT_MIN}`
    if [[ ${RE} = "<" ]]; then
      COMPONENT_MIN=${COMPONENT_VERSION}
    fi
  done

  # if lowest required version is lower than lowest compatible version, abort
  RE=`OvCslCmpVersions ${COMPONENT_MIN} ${LOWEST_SUPPORTED}`
  if [[ ${RE} = "<" ]]; then

  OvCslLog "$COMPONENT_ID" "conflict: lowest required version '${COMPONENT_MIN}' is lower than lowest
  supported '${LOWEST_SUPPORTED}'" "Conflict in Compatibility Matrix"

    return 1
  fi

  if [[ x = x"${SUPPORTED_VERSIONS}" ]]; then
    SUPPORTED_VERSIONS=${CURRENT_VERSION}
    SUPPORTED_VERSIONS=${CURRENT_VERSION}
  fi

  # if lowest required version 
  RE=`OvCslCmpVersions ${CURRENT_VERSION} ${SUPPORTED_VERSIONS}`
  if [[ ${RE} = "<" ]]; then

  OvCslLog "$COMPONENT_ID" "conflict: current version '${CURRENT_VERSION}' lower than
  '${SUPPORTED_VERSIONS}'" "Conflict in Compatibility Matrix"
 
   return -1
  fi

  # check if there are any other dependencies to older versions of the component
  OvCslCheckDependencies ${COMPONENT_ID} ${SUPP_VER}
  RC=$?

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

## FUNCTION:     OvCslWriteComponentVersions
## DESCRIPTION:  Updates the component version table
## PARAMETERS:   $1: Component ID  (see file header comment for more info)
##               $2: current version of component
##               $3: lowest compatible version
##               $4: (optional) -multiple 
## RETURN VAL:    0: No error encountered
##                $OVCSL_ERROR_WRITING_FILE: Error writing file
## RETURN ECHO:  

OvCslWriteComponentVersions()
{
  COMPONENT_ID=$1
  CURRENT_VERSION=$2
  LOWEST_SUPPORTED=$3
  if [ ! -z "$4" ]; then
    MULT=1
  else
    MULT=0
  fi

  COMPONENT_FILE=${OVCSL_COMPONENT_MATRIX_FILE}
  PRODUCT_FILE=${OVCSL_PRODUCT_MATRIX_FILE}
  
  # DEPRECATED (OvCsl02.00) BEGIN
  # workaround for a bug in previous versions of this library
  if [ -f "$OVCSL_OV_DATA_CONF/product.cfg" ]; then
    /bin/cat "$OVCSL_OV_DATA_CONF/product.cfg" >> $PRODUCT_FILE
    /bin/rm -f "$OVCSL_OV_DATA_CONF/product.cfg"
  fi
  # DEPRECATED (OvCsl02.00) END

  # delete all lines with the current component (should only be one), write result to tmp file
  if [ $MULT -eq 0 ]; then
    if [[ -f ${COMPONENT_FILE} ]]; then 
      SEDSTRING='/^'${COMPONENT_ID}'/d'
      sed -e ${SEDSTRING} ${COMPONENT_FILE} > ${COMPONENT_FILE}.tmp
    fi
  else
    if [[ -f ${COMPONENT_FILE} ]]; then 
      SEDSTRING='/^'${COMPONENT_ID}.${CURRENT_VERSION}'/d'
      sed -e ${SEDSTRING} ${COMPONENT_FILE} > ${COMPONENT_FILE}.tmp
    fi
  fi

  # create conf directory if not already present
  if [[ ! -d ${OVCSL_OV_DATA_CONF} ]]; then
    /bin/mkdir -p -m 775 ${OVCSL_OV_DATA_CONF}
  fi

  # add new line to the tmp file
  if ! echo ${COMPONENT_ID}"	"${CURRENT_VERSION}"	"${LOWEST_SUPPORTED}"	"${OVCSL_INSTALL_DATE} >> ${COMPONENT_FILE}.tmp; then
    return $OVCSL_ERROR_WRITING_FILE
  fi

  # sort tmp file according to component ID and write it back to original file
  /bin/cat ${COMPONENT_FILE}.tmp | sort > ${COMPONENT_FILE}
  if [[ -f ${COMPONENT_FILE}.tmp ]]; then 
    /bin/rm -f ${COMPONENT_FILE}.tmp

  fi

}

## FUNCTION:     OvCslRemoveComponentVersions
## DESCRIPTION:  Updates the component version table
## PARAMETERS:   $1: Component ID  (see file header comment for more info)
##               $2: version that is deleted
## RETURN VAL:    0: No error encountered
##               $OVCSL_ERROR_WRITING_FILE: Error writing file
## RETURN ECHO:  

OvCslRemoveComponentVersions()
{
  COMPONENT_ID=$1
  COMPONENT_VER=$2

  if [[ ! -d ${OVCSL_OV_DATA_CONF} ]]; then
    return 0
  fi
    
  COMPONENT_FILE=${OVCSL_COMPONENT_MATRIX_FILE}
  PRODUCT_FILE=${OVCSL_PRODUCT_MATRIX_FILE}
  DEP_FILE=${OVCSL_DEPENDENCY_MATRIX_FILE}

  # DEPRECATED (OvCsl02.00) BEGIN
  # workaround for a bug in previous versions of this library
  if [ -f "$OVCSL_OV_DATA_CONF/product.cfg" ]; then
    /bin/cat "$OVCSL_OV_DATA_CONF/product.cfg" >> $PRODUCT_FILE
    /bin/rm -f "$OVCSL_OV_DATA_CONF/product.cfg"
  fi
  # DEPRECATED (OvCsl02.00) END
  
  # delete all lines with the current component (should only be one), write result to tmp file
  if [[ -f ${COMPONENT_FILE} ]]; then
    SEDSTRING='/^'${COMPONENT_ID}.${COMPONENT_VER}'/d'
    sed -e ${SEDSTRING} ${COMPONENT_FILE} > ${COMPONENT_FILE}.tmp

    if ! /bin/mv ${COMPONENT_FILE}.tmp ${COMPONENT_FILE}; then
      return $OVCSL_ERROR_WRITING_FILE
    fi

    # remove component matrix if it is empty
    if [[ ! -s ${COMPONENT_FILE} ]]; then
      /bin/rm -f ${COMPONENT_FILE}
    fi
  fi

  # delete all lines with the current component in the product file (should only be one), write result to tmp file
  if [[ -f ${PRODUCT_FILE} ]]; then
    typeset wspaces=`echo -e " \t\v"`
    SEDSTRING="/[$wspaces]${COMPONENT_ID}[$wspaces]/d"
    sed -e "${SEDSTRING}" ${PRODUCT_FILE} > ${PRODUCT_FILE}.tmp

    if ! /bin/mv ${PRODUCT_FILE}.tmp ${PRODUCT_FILE}; then
      return $OVCSL_ERROR_WRITING_FILE
    fi
  fi

  # delete all lines with the current component in the dependecy file write result to tmp file
  if [[ -f ${DEP_FILE} ]]; then
    SEDSTRING='/^'${COMPONENT_ID}.${COMPONENT_VER}'/d'
    sed -e ${SEDSTRING} ${DEP_FILE} > ${DEP_FILE}.tmp

    if ! /bin/mv ${DEP_FILE}.tmp ${DEP_FILE}; then
      return $OVCSL_ERROR_WRITING_FILE
    fi

    # remove DependencyMatrix if empty
    if [[ ! -s ${DEP_FILE} ]]; then
      /bin/rm -f ${DEP_FILE}
    fi
  fi

  return 0
}

## FUNCTION:     OvCslWriteDependencies
## DESCRIPTION:  Updates the dependency table
## PARAMETERS:   $1: Component/Product ID  (see file header comment for more info)
##               $2: version of component/product
##               $3: component ID, that the current comp/prod depends upon
##               $4: version of the component that the current comp/prod depends upon
##               $5: (optional) -multiple
## RETURN VAL:    0: No error encountered
##               $OVCSL_ERROR_WRITING_FILE: Error writing file
## RETURN ECHO:  

OvCslWriteDependencies()
{

  DEP_FILE=${OVCSL_DEPENDENCY_MATRIX_FILE}
  COMPONENT_ID=$1
  COMPONENT_VER=$2
  DEP_ID=$3
  DEP_VER=$4
  if [ ! -z "$5" ]; then
    MULT=1
  else
    MULT=0
  fi

  # delete the line which has current component id and depending id
  # should only be necessary during upgrade
  if [[ -f ${DEP_FILE} ]]; then
    if [ $MULT -eq 0 ]; then
      SEDSTRING='/^'${COMPONENT_ID}.*${DEP_ID}'/d'
      sed -e ${SEDSTRING} ${DEP_FILE} > ${DEP_FILE}.tmp
    else
      SEDSTRING='/^'${COMPONENT_ID}.${COMPONENT_VER}.*${DEP_ID}'/d'
      sed -e ${SEDSTRING} ${DEP_FILE} > ${DEP_FILE}.tmp
    fi
  fi

  # add new line to the tmp file
  if ! echo ${COMPONENT_ID}"	"${COMPONENT_VER}"	"${DEP_ID}"	"${DEP_VER} >> ${DEP_FILE}.tmp; then
    return $OVCSL_ERROR_WRITING_FILE
  fi

  # sort tmp file according to component ID and write it back to original file
  /bin/cat ${DEP_FILE}.tmp | sort > ${DEP_FILE}
  if [[ -f ${DEP_FILE}.tmp ]]; then 
    /bin/rm -f ${DEP_FILE}.tmp
  fi

  return 0
}

## FUNCTION:     OvCslRemoveDependencies
## DESCRIPTION:  Updates the dependency table
## PARAMETERS:   $1: Component/Product ID  (see file header comment for more info)
## RETURN VAL:    0: No error encountered
##               $OVCSL_ERROR_WRITING_FILE: Error writing file
## RETURN ECHO:  

OvCslRemoveDependencies()
{

  DEP_FILE=${OVCSL_DEPENDENCY_MATRIX_FILE}
  COMPONENT_ID=$1

  # delete the line which has current component id and depending id
  # should only be necessary during upgrade
  if [[ -f ${DEP_FILE} ]]; then
    SEDSTRING='/^'${COMPONENT_ID}'/d'
    sed -e ${SEDSTRING} ${DEP_FILE} > ${DEP_FILE}.tmp

    # sort tmp file according to component ID and write it back to original file
    /bin/cat ${DEP_FILE}.tmp | sort > ${DEP_FILE}
    if [[ -f ${DEP_FILE}.tmp ]]; then 
      /bin/rm -f ${DEP_FILE}.tmp
    fi

    # remove DependencyMatrix if empty
    if [[ ! -s ${DEP_FILE} ]]; then
      /bin/rm -f ${DEP_FILE}
    fi
  fi

  return 0
}

## FUNCTION:     OvCslCheckDependencies
## DESCRIPTION:  Checks whether an update would break any dependencies
## PARAMETERS:   $1: component ID, that the current comp/prod depends upon
##               $2: lowest supported component Ver of the comp, that the current comp/prod depends upon
## RETURN VAL:    0: update may be performed
##                1: update would break dependency
## RETURN ECHO:  

OvCslCheckDependencies()
{

  DEP_FILE=${OVCSL_DEPENDENCY_MATRIX_FILE}
  DEP_ID=$1
  SUPP_VER=$2

  if [ ! -f ${DEP_FILE} ]; then
    # there is no dependency matrix yet, so no problems upgrading
    return 0
  fi

  #DEP_VERS=`grep -e "${DEP_ID} *" ${DEP_FILE} | grep -v "^${DEP_ID}" | awk '{ print $4 }'`
  DEP_VERS=`grep -e "[[:space:]]\{1,\}${DEP_ID}[[:space:]]\{1,\}" ${DEP_FILE} | awk '{ print $4 }'`
    
  if [ a = a"${DEP_VERS}" ]; then
    # the component/product does not yet appear in the dependency matrix
    return 0
  fi

  # determine minimal required version
  COMPONENT_MIN_MAJOR=999
  COMPONENT_MIN_MINOR=0
  for i in ${DEP_VERS}; do
    COMPONENT_VERSION_MAJOR=`echo ${i} | cut -f 1 -d .`
    COMPONENT_VERSION_MINOR=`echo ${i} | cut -f 2 -d .`
    if [[ ${COMPONENT_VERSION_MAJOR} -lt ${COMPONENT_MIN_MAJOR} ]]; then
      COMPONENT_MIN_MAJOR=${COMPONENT_VERSION_MAJOR}
      COMPONENT_MIN_MINOR=${COMPONENT_VERSION_MINOR}
    else
      if [[ ${COMPONENT_VERSION_MAJOR} -eq ${COMPONENT_MIN_MAJOR} ]]; then
        if [[ ${COMPONENT_VERSION_MINOR} -lt ${COMPONENT_MIN_MINOR} ]]; then
          COMPONENT_MIN_MINOR=${COMPONENT_VERSION_MINOR}
        fi
      fi
    fi
  done

  # split minimum compatible version, so that it can be compared
  
  SUPP_VER_MAJOR=`echo ${SUPP_VER} | cut -f 1 -d . | sed 's/^0*//'`
  SUPP_VER_MINOR=`echo ${SUPP_VER} | cut -f 2 -d . | sed 's/^0*//'`

  if [[ ${COMPONENT_MIN_MAJOR} -lt ${SUPP_VER_MAJOR} ]]; then
    return 1
  else
    if [[ ${COMPONENT_MIN_MAJOR} -eq ${SUPP_VER_MAJOR} ]]; then
      if [[ ${COMPONENT_MIN_MINOR} -lt ${SUPP_VER_MINOR} ]]; then
        return 1
      else
        return 0
      fi
    else
      return 0
    fi
  fi
}

INI_HEADER="[ovinstaller.properties]"
iniFileName="/var/tmp/ovinstallparams.ini"

DEFAULT_LOG_FILE="/var/tmp/HPOvPerfAgt-install.log"
LOG_FILE=`OvCslReadINIString ${INI_HEADER} "LOGFILE" ${DEFAULT_LOG_FILE} ${iniFileName}`

export OVCSL_LOG="TRUE"
export OVCSL_LOG_APPLICATION="HPOvPerfAgt"
export OVCSL_LOG_FILE=${LOG_FILE}

typeset loggedBy="configure"
typeset argvalue="-u"

OvCslInstallDirectory /opt/OV/newconfig bin bin 555
OvCslInstallDirectory /opt/OV/man bin bin 555
OvCslInstallDirectory  ${OVCSL_OV_DATA_CONF}/perf bin bin 0555 $TRUE

   ECHOCMD=echo

comp_vers="11.0"
comp_name="OvPerfAgt"

if [ "$1" = "${argvalue}" ]
then
    OvCslLog $loggedBy "info" "unconfigure parameters as cleanall option selected"
    # Remove config file
    OvCslLog $loggedBy  "info" "Remove config files"
    if [ -f /var/opt/perf/reptall ]
    then
        /bin/rm -f /var/opt/perf/reptall
    fi   
    if [ -f /var/opt/perf/repthead ]
    then
        /bin/rm -f /var/opt/perf/repthead
    fi
    if [ -f /var/opt/perf/reptfile ]
    then
        /bin/rm -f /var/opt/perf/reptfile
    fi
    if [ -f /var/opt/perf/repthist ]
    then
        /bin/rm -f /var/opt/perf/repthist
    fi
    if [ -f /var/opt/perf/rxitemid ]
    then
        /bin/rm -f /var/opt/perf/rxitemid
    fi
    if [ -f /var/opt/perf/rxshorts ]
    then
        /bin/rm -f /var/opt/perf/rxshorts
    fi

    if [ -f ${OVCSL_OV_DATA}/installation/inventory/HPOvPCO.xml ]
    then
        /bin/rm -f ${OVCSL_OV_DATA}/installation/inventory/HPOvPCO.xml
    fi
    if [ -f /var/opt/perf/alarmdef ]
    then
        /bin/rm -f /var/opt/perf/alarmdef
    fi
    if [ -f /var/opt/perf/parm ]
    then
        /bin/rm -f /var/opt/perf/parm
    fi
    if [ -f /var/opt/OV/conf/perf/datasources ]
    then
        /bin/rm -f /var/opt/OV/conf/perf/datasources
    fi
    if [ -f ${OVCSL_OV_DATA}/installation/inventory/HPOvPerfAgt.xml ]
    then
        /bin/rm -f ${OVCSL_OV_DATA}/installation/inventory/HPOvPerfAgt.xml
    fi
    
    if [ -d ${OVCSL_OV_DATA_CONF}/oa/Model ]
    then
        /bin/rm -f -r ${OVCSL_OV_DATA_CONF}/oa/Model/*
    fi
    
    if [ -d ${OVCSL_OV_DATA}/datafiles/oacore.oacore.pid ]
    then
        /bin/rm -f ${OVCSL_OV_DATA}/datafiles/oacore.oacore.pid
    fi

exit 0 
fi

###################
## 1. create necessary directories if not already present
OvCslLog $loggedBy "info" "Creating necessary directories:"
OvCslInstallDirectory ${OVCSL_OV_DATA}/databases/oa bin bin 755 $TRUE
# OvCslInstallDirectory ${OVCSL_OV_DATA_DATABASES}/oa bin bin 755 $TRUE

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

###################
## 2. write dependency matrix
OvCslLog $loggedBy "info" "Writing dependency matrices."
OvCslWriteComponentVersions "OpsAgt" "1.0" "1.0"
OvCslWriteDependencies "OpsAgt" "1.00" "OvBbc" "11.00"
OvCslWriteDependencies "OpsAgt" "1.00" "OvSecCo" "11.00"
OvCslWriteDependencies "OpsAgt" "1.00" "OvXpl" "11.00"
###################

###################
### 3. copy config files
OvCslLog $loggedBy "info" "Copy config files"
if [[ -f /opt/perf/newconfig/oacore_def.ini && -d ${OVCSL_OV_ROOT}/misc/xpl/config/defaults/ ]]; then
    /bin/cp -f /opt/perf/newconfig/oacore_def.ini ${OVCSL_OV_ROOT}/misc/xpl/config/defaults/
fi

OvCslInstallDirectory  ${OVCSL_OV_DATA_CONF}/oa bin bin 0555 $TRUE

OvCslInstallDirectory  ${OVCSL_OV_DATA_CONF}/oa/Model bin bin 0555 $TRUE

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/DMLMetaMetaSchema && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/DMLMetaMetaSchema ${OVCSL_OV_DATA_CONF}/oa/Model
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/DiskMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/DiskMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/NetworkMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/NetworkMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/TransactionMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/TransactionMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/ProcessMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/ProcessMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/CpuMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/CpuMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/CoreMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/CoreMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/ApplicationMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/ApplicationMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/FileSysMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/FileSysMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/Global.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/Global.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/HbaMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/HbaMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

if [[ -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/LogicalVolumeMetricModel.xml && -d ${OVCSL_OV_DATA_CONF}/oa/Model/ ]]; then
    /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/Model/LogicalVolumeMetricModel.xml ${OVCSL_OV_DATA_CONF}/oa/Model/
fi

OvCslInstallDirectory  ${OVCSL_OV_DATA_CONF}/oa/PipeDefinitions bin bin 0555 $TRUE

# upgrade from 11.1x to 12.x change

OvCslIsComponentConfigured "HPOvEaAgt"
if [ $? -eq 0 ]
then
    if [ -f ${OVCSL_OV_DATA_CONF}/ctrl/coda.xml ]
    then
        OvCslLog $loggedBy "info" "De-registering coda from Control Core."
        OvCslCtrlUnregComponent "coda"
        if [ $? -ne 0 ]
        then
            OvCslStrMsgFmt 4 "Could not unregister coda at OVControl"
            OvCslLog $loggedBy "error" "Failed to de-register coda from Control Core."
        fi
    fi
fi

CTRL_REG_FILE=${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/ctrl/oacore.xml
PIPE_DEFN_FILE=${OVCSL_OV_NEW_CONFIG}/DataDir/conf/OpsAgt/PipeDefinitions/oacore.xml

#Added Registering oacore to Ctrl for VirtMan
if OvCslCtrlRegComponent ${CTRL_REG_FILE}
then
    OvCslLog ${loggedBy} "info" "Registered oacore with OV Control"
else
    OvCslLog ${loggedBy} "error" "Could not register oacore with OV Control"
fi

if [[ -f ${PIPE_DEFN_FILE} ]]; then
	/bin/cp -f ${PIPE_DEFN_FILE} ${OVCSL_OV_DATA_CONF}/oa/PipeDefinitions/oacore.xml
fi

#Created the DB directory in data dir for VirtMan in Step 2
#Creating oa.db using sqlite command.
skipDBCreation=0
forceDBCreation=0
OvCslIsComponentConfigured "HPOvEaAgt"
if [ $? -eq 0 ]
then
   ver=`cat ${OVCSL_OV_DATA}/installation/inventory/HPOvEaAgt.xml | grep "<version>" | cut -d">" -f2 | cut -d"<" -f1 | tail -1`
   majVer=`echo $ver | cut -d. -f1`

   if [ `${ECHOCMD} ${ver} | tr -d '.'` -ge `${ECHOCMD} 1200050` ] && [ `${ECHOCMD} ${ver} | tr -d '.'` -lt `${ECHOCMD} 1200073` ]
   then
       forceDBCreation=1
   fi

   if [ $majVer -ge 12 -a $forceDBCreation -eq 0 ]
   then
       skipDBCreation=1
   fi

fi
    if [ $skipDBCreation -eq 0 ]
    then
       SQLLITE="$OVCSL_OV_BIN/sqlite3"

       if [ -x ${SQLLITE} ]; then

                OvCslLog ${loggedBy} "info" "Creating oa.db using sqlite3"
                ${SQLLITE} ${OVCSL_OV_DATA}/databases/oa/oa.db < ${OVCSL_OV_DATA}/conf/oa/Model/DMLMetaMetaSchema > /dev/null
                if [ $? -ne 0 ]
                then
                    OvCslLog ${loggedBy} "error" "Creating the oa.db failed"
                else
                    OvCslLog ${loggedBy} "info" "Created the oa.db sucessfully"
                fi
      fi
   else
       OvCslLog ${loggedBy} "info" "OA DB creation will be skipped for upgrade from agent version greater than 12.00"
   fi

OvCslLog ${loggedBy} "info" "Setting updated model to true"
OvCslXplConfChange "oacore" "UPDATED_MODEL_AVAILABLE" "TRUE"

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

OvCslWriteComponentVersions "$comp_name" "$comp_vers" "11.0"

OvCslWriteDependencies "$comp_name" "$comp_vers" "OvXpl" "11.00"
OvCslWriteDependencies "$comp_name" "$comp_vers" "OvSecCo" "11.00"
OvCslWriteDependencies "$comp_name" "$comp_vers" "OvPacc" "11.00"
OvCslWriteDependencies "$comp_name" "$comp_vers" "OvPerfMI" "11.00"

# ###############################################################################
# ###############################################################################
# FUNCTIONS
#
# Display messages

oops () {
  case $1 in
    -w) preface="WARNING: "; shift;;
    -n) preface="NOTE:    "; shift;;
    -e) preface="ERROR:   "; shift;;
    *)  preface="ERROR:   ";;
  esac
  while [ $# -gt 0 ]; do
    logerr "${preface}$1"
    preface="         "
    shift
  done
} # oops

logerr() {
   echo "$@" >&2
 }

# cond_cpset
#
# Usage: cond_cpset mode owner group source target
#
#       $1:     mode
#       $2:     owner (uid)
#       $3:     group (gid)
#       $4:     copy fromfile
#       $5:     copy destination path
#
#    iff $5 doesn't exist, copy $4 to $5 and set attributes.
#       Return 0 if $5 already exists or if copy and set succeeds
#       Return 1 if copy or set attempt fails
#
 cond_cpset ()
   {
    if [ $# -ne 5 ]; then
		OvCslLog $loggedBy "error" "Usage: cond_cpset mode owner group source target."
        return 1
    fi

    if [ ! -f "$5" ]; then
	    OvCslLog $loggedBy "info" "Copying $4 to $5 with following file attribute filemode : $1 , filegroup : $3, fileownership : $2"
        OvCslInstallFile $4 $5 $2 $3 $1
    fi
    return 0
   }
   
addappl ()
{
typeset FileName=$1
typeset line=""
count=0
typeset applfound=0
typeset section="application = OperationsAgent"

/bin/rm -f /tmp/tempparm 2>&1 >/dev/null
/bin/rm -f /tmp/parm_var 2>&1 >/dev/null

if [ -f /var/opt/perf/parm ]
then
   /bin/cat /var/opt/perf/parm | grep -i "application = OperationsAgent" 2>&1 >/dev/null
   retval=$?
   if [ $retval -ne 0 ]; then
      OvCslLog $loggedBy "info" "Copying the application = OperationsAgent section to the parm file."
      while read line
      do
       count=`expr ${count} + 1`
       if [ "X${line}" = "X${section}" ]
       then
           sectionFound=1
           ${ECHOCMD} " " >> /tmp/tempparm
           x=`grep -n "application = OperationsAgent" ${FileName}  | cut -f1 -d:`
           x=`expr $x - 2`
           awk -v ln=$x 'NR>=ln && NR<=ln+7' ${FileName} >> /tmp/tempparm
           ${ECHOCMD} " " >> /tmp/tempparm
           break
       fi
      done < ${FileName}
      while read line
      do
         ${ECHOCMD} "${line}" >> /tmp/new_parm
         ${ECHOCMD} "${line}" | grep -n "^application =" 2>&1 >/dev/null
         if [ $? -eq 0 ]
         then
             applfound=`expr ${applfound} + 1`
         fi

         if [ ${applfound} -eq 1 ]
         then
             ${ECHOCMD} "${line}" | grep -n "^$"  2>&1 >/dev/null
             if [ $? -eq 0 ]
             then
                 /bin/cat /tmp/tempparm >> /tmp/new_parm
             fi
         fi
      done < /var/opt/perf/parm
      cp_set 644 root bin /tmp/new_parm /var/opt/perf/parm
      /bin/rm -f /tmp/tempparm 2>&1 >/dev/null
      /bin/rm -f /tmp/new_parm 2>&1 >/dev/null
   fi
fi

}

#
########
# cp_set
#
# Usage: cp_set mode owner group source target
#
#       $1:     mode
#       $2:     owner (numeric uid)
#       $3:     group (numeric gid)
#       $4:     copy fromfile
#       $5:     copy destination path
#
#    unconditionally copy $4 to $5 and set attributes
#
########
cp_set ()
{
   if [ $# -ne 5 ]
   then
	  OvCslLog $loggedBy "error" "Usage: cp_set mode owner group source target."
      return 1
   fi
   OvCslLog $loggedBy "info" "Copying $4 to $5 with following file attribute filemode : $1 , filegroup : $3, fileownership : $2"
   /bin/cp -f  $4 $5 || return 1

   if [ -d "$5" ]
   then
      /bin/chmod "$1" "$5/${4##*/}" || return 1
      /bin/chgrp "$3" "$5/${4##*/}" || return 1
      /bin/chown "$2" "$5/${4##*/}" || return 1
   else
      /bin/chmod "$1" "$5" || return 1
      /bin/chgrp "$3" "$5" || return 1
      /bin/chown "$2" "$5" || return 1
   fi
   return 0
}

#######
# cond_cp
#
# Usage: cond_cp source target
#
#    iff target doesn't exist, copy source to target and retain attributes.
#
########

cond_cp ()
{
    if [ $# -ne 2 ]
    then
        echo "Usage: cond_cp source target" >&2
        return 1
    fi

    if [ ! -f "$2" ]
    then
	     OvCslLog $loggedBy "info" "Copying $1 to $2"
        /bin/cp -f -p $1 $2 || return 1
    fi
    return 0
}

funcREMV_FILE()
  {
   for FILE in $*
    do
     if [ -f $FILE ] || [ -h $FILE ]; then
         OvCslLog $loggedBy "info" "Removing $FILE"
		 /bin/rm -f -f $FILE
     fi
    done
   }

# Conditionally make a directory with permissions and group
# syntax:  mkdir_set directory_name permissions groupname
#
mkdir_set () 
{
    if [ ! -d $1 ]; then
        mkdir $1
        if [ $? -ne 0 ]; then
           logerr "Could not mkdir \"$1\""
           ERROR=1
        fi
        if [ -n $2 ]; then
           /bin/chmod $2 $1
           if [ $? -ne 0 ]; then
              logerr "Could not chmod $2 \"$1\""
              ERROR=1
           fi
        fi
        if [ -n $3 ]; then
           /bin/chgrp $3 $1
           if [ $? -ne 0 ]; then
              logerr "Could not /bin/chgrp $2 \"$1\""
              ERROR=1
           fi
        fi
     fi
}

 set -a                        # Export all vars
 exitval=$SUCCESS                # Anticipate success
# ########################################################################

# FUNCTIONS TO: "Completely delete a particular file or Dir if it exists"

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

EGREP="/bin/egrep"
   OV_PERF="/opt/perf"
   OVDIR="/opt/OV"
NEW="${OV_PERF}/newconfig"
DEFAULT="/etc/default"

# Determine what linux platform:
# files to move init.ovpa & rc.config.ovpa

# FIND RIGHT rc DIRECTORY PATH

 # ############################################
 # RedHat / TurboLinux - today
 # SuSE future
 # Debian future

 # ############################################
 # Future plan to use LSB STANDARD LOCATION
 # 
 # OVPA System Startup and ShutDown Script
 # OVPA ovpa rc links
 # --------------------------------
 # ROSmm26932 removed links with rc3 and rc5. Therefore the postinstall
 # has those lines commented out, but were left in the postremove script
 # for cleanup. Once testing is done all references in postinstall and
 # postremove for rc3&5 will be removed prior to MR.
 #  - On 30Jan03 Anne requested uncomment the rc3 links as appears to be
 # needed. She will test all Linux platforms/OSs to verify once the
 # update is packaged
 #  - AnneM: Needed to uncomment the rc5 link for Red Hat & TurboLinux;
 #    changed the if/else to elif; corrected the rc paths for SuSE 7.1
 #    and newer releases.
 # --------------------------------

 OvCslLog $loggedBy "info" "Updating Performance agent Startup and ShutDown Script"

/bin/rm -f /etc/rc.d/init.d/ovpa /sbin/init.d/ovpa /etc/init.d/ovpa >/dev/null 2>&1 
MANUAL_START_ON_REBOOT=`OvCslReadINIString ${INI_HEADER} "MANUAL_START_ON_REBOOT" "FALSE" ${iniFileName}`
if [ "x${MANUAL_START_ON_REBOOT}" != "xTRUE" ]
then
 
 if [ -d /etc/rc.d/init.d ]; then
    # --------------------------------
    # RedHat / TurboLinux
    # --------------------------------
    /bin/cp -f /opt/perf/newconfig/init.d/ovpa /etc/rc.d/init.d/ovpa
    /bin/ln -f -s /etc/rc.d/init.d/ovpa /etc/rc.d/rc2.d/S96ovpa
    /bin/ln -f -s /etc/rc.d/init.d/ovpa /etc/rc.d/rc3.d/S96ovpa
    /bin/ln -f -s /etc/rc.d/init.d/ovpa /etc/rc.d/rc5.d/S96ovpa
    /bin/ln -f -s /etc/rc.d/init.d/ovpa /etc/rc.d/rc0.d/K08ovpa
    /bin/ln -f -s /etc/rc.d/init.d/ovpa /etc/rc.d/rc6.d/K08ovpa
 elif [ -d /sbin/init.d ]; then
    # --------------------------------
    # SuSE up through 7.0 uses /sbin/init.d
    # --------------------------------
    /bin/cp -f /opt/perf/newconfig/init.d/ovpa /sbin/init.d/ovpa
    /bin/ln -f -s  /sbin/init.d/ovpa /sbin/init.d/rc2.d/S96ovpa
    /bin/ln -f -s  /sbin/init.d/ovpa /sbin/init.d/rc3.d/S96ovpa
    /bin/ln -f -s  /sbin/init.d/ovpa /sbin/init.d/rc5.d/S96ovpa
    /bin/ln -f -s  /sbin/init.d/ovpa /sbin/init.d/rc0.d/K08ovpa
    /bin/ln -f -s  /sbin/init.d/ovpa /sbin/init.d/rc6.d/K08ovpa
 elif [ -d /etc/rc2.d ]; then
    # --------------------------------
    # Debian 
    # --------------------------------
    /bin/cp -f /opt/perf/newconfig/init.d/ovpa /etc/init.d/ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc2.d/S96ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc3.d/S96ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc5.d/S96ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc0.d/K08ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc6.d/K08ovpa
 elif [ -d /etc/init.d/rc2.d ]; then 
    # --------------------------------
    # SuSE 7.1 and newer
    # --------------------------------
    /bin/cp -f /opt/perf/newconfig/init.d/ovpa /etc/init.d/ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc.d/rc2.d/S96ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc.d/rc3.d/S96ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc.d/rc5.d/S96ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc.d/rc0.d/K08ovpa
    /bin/ln -f -s  /etc/init.d/ovpa /etc/rc.d/rc6.d/K08ovpa
 fi
 if [ -f /etc/SuSE-release ]; then
    if [ -f /sbin/insserv ]; then
       insserv /etc/init.d/ovpa 2> /dev/null
    fi
 fi
fi

  IS_VIMA=0
  function is_vima()
  {
   if [ -f /opt/perf/newconfig/.vima ]; then
     IS_VIMA=1
   fi
  }
   is_vima 
   # Enable BBC port
   if [ $IS_VIMA -eq 1 ]; then  # Need not check for is_unsupported_vima, as it is already checked once
      iptables -L | grep -w "hp-alarm-mgr" | grep -w ACCEPT > /dev/null
    if [ $? -ne 0 ]; then
       iptables -I RH-Firewall-1-INPUT 4 -p tcp -m tcp --dport 383 --tcp-flags SYN,RST,ACK SYN -j ACCEPT 2>/dev/null
       if [ $? -eq 1 ]; then
          OvCslLog $loggedBy "info" "Not able to enable BBC default port 383 for remote communication."
       else
          OvCslLog $loggedBy "info" "Enabling default port for BBC."
       fi
    fi
  fi

 cond_cpset 644 root bin $NEW/reptall /var/opt/perf/reptall
 cond_cpset 644 root bin $NEW/reptfile /var/opt/perf/reptfile

 ENABLE_PERFALARM=`OvCslReadINIString ${INI_HEADER} "ENABLE_PERFALARM" "FALSE" ${iniFileName}`
 if [ "X$ENABLE_PERFALARM" = "XTRUE" ]
 then
     OvCslLog $loggedBy "info" "perfalarm is enabled here"
     cond_cpset 644 root bin $NEW/alarmdef /var/opt/perf/alarmdef
 fi

OvCslIsComponentConfigured "HPOvEaAgt"
if [ $? -eq 0 ]
then
   ver=`cat ${OVCSL_OV_DATA}/installation/inventory/HPOvEaAgt.xml | grep "<version>" | cut -d">" -f2 | cut -d"<" -f1 | tail -1`
   if [ `${ECHOCMD} ${ver} | tr -d '.'` -ge `${ECHOCMD} 1200050` ] && [ `${ECHOCMD} ${ver} | tr -d '.'` -lt `${ECHOCMD} 1200073` ]
   then
       OvCslLog $loggedBy "info" "Overwriting parm file at /var/opt/perf/parm "
       cp_set 644 root bin $NEW/parm /var/opt/perf/parm
   fi
fi

 cond_cpset 644 root bin $NEW/parm /var/opt/perf/parm
 if [ -f /var/opt/perf/parm ]
 then
    addappl $NEW/parm
 fi
 
 cond_cpset 644 root bin $NEW/baseline.cfg /var/opt/perf/baseline.cfg

if [ -f /var/opt/perf/perflbd.rc ] ; then
   /bin/rm -f  /var/opt/perf/perflbd.rc > /dev/null 2>&1
fi

## check for older database files and move them to newer directory
if [ -e ${OVCSL_OV_DATA}/databases/coda.db ]; then
  typeset my_model=`${OVCSL_UNAME} -m`
  typeset my_os=`${OVCSL_UNAME} -s`
  typeset my_kernel=`${OVCSL_UNAME} -r | ${OVCSL_CUT} -f1,2 -d.`
  typeset doMigrate=1

   # Check for Linux 2.6_64 and 2.6 ia64    
   if [[ ${my_os} = "Linux" && ${my_kernel} = "2.6" ]]; then
     case ${my_model} in
       ia64) doMigrate=0
          ;;
       x86_64) doMigrate=0
          ;;
     esac
   fi
   if [ ${doMigrate} -eq 0 ]; then
      OvCslXplTrace "32 to 64 bit upgrade detected, DB files will not be migrated"
   else
      OvCslXplTrace "Migrate coda database files to datafiles directory."
      /bin/mv ${OVCSL_OV_DATA}/databases/coda* ${OVCSL_OV_DATA_DATAFILES}/.
   fi
fi

     if [[ -f /opt/perf/newconfig/common_oa_def.ini && -d ${OVCSL_OV_ROOT}/misc/xpl/config/defaults ]]; then
        /bin/cp -f /opt/perf/newconfig/common_oa_def.ini ${OVCSL_OV_ROOT}/misc/xpl/config/defaults
     fi

## if a group is defined in XPL, change group ownerships of files
typeset my_group=`OvCslXplConfGet xpl.install group`

if [ -n "${my_group}" ]; then
  ${OVCSL_OV_BIN}/ovswitchuser.sh -setgroup HPOvPerfAgt
fi

# #if defined (_Linux2_6_64_) || defined(_Linux2_6_)
# if [ "x$NEXTGENAGT" = "xFALSE" -a ! -f /var/opt/OV/datafiles/ngconfigured ]
# then
# #endif
# #if defined (_Linux2_6_64_) || defined(_Linux2_6_)
# if [ ! -f ${OVCSL_OV_DATA}/datafiles/perfagtconfigured ]
# then
#     touch ${OVCSL_OV_DATA}/datafiles/perfagtconfigured
#     chmod 660 ${OVCSL_OV_DATA}/datafiles/perfagtconfigured  
# fi
# #endif
# 
# #if defined (_Linux2_6_64_) || defined(_Linux2_6_)
# fi ###### NEXTGENAGT is false.
# #endif

######## Added the below code for AR context ##################

## copy deployment descriptor for PerfAgt
if [[ -f ${OVCSL_OV_NEW_CONFIG}/installation/inventory/HPOvPerfAgt.xml && -d ${OVCSL_OV_DATA}/installation/inventory ]]; then
   /bin/cp -f ${OVCSL_OV_NEW_CONFIG}/installation/inventory/HPOvPerfAgt.xml ${OVCSL_OV_DATA}/installation/inventory
fi 

###################
###  Remove the Component patch inventory xml files from DataDir inventory location

OvCslRemovePatchInventoryFiles HPOvPerfAgt

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

exit $exitval

exit 0