#!/usr/bin/ksh93
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r714 src/43haes/usr/sbin/cluster/sa/filenet/sbin/cl_filenet_was_AE_CE_import.sh 1.1 
#  
# Licensed Materials - Property of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2010 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# @(#)90	1.1  src/43haes/usr/sbin/cluster/sa/filenet/sbin/cl_filenet_was_AE_CE_import.sh, hacmp, 61haes_r714 11/28/11 15:25:20
###################################################################
##
## NAME:    cl_filenet_was_AE_CE_import
##
## DESCRIPTION:    
##    Makes the necessary configuration changes to HACMP and 
##    WebSphere to create or remove highly available WebSphere Node, 
##    Deployment Manager, or IBM Http Server.  
##    
##    When adding, an HACMP resource group will be created along 
##    with a the following HACMP resources
##        Service Label
##        Application Monitor
##        Application Server
##    After the resources are created, the WebSphere components will 
##    be updated to listen on the new service IP label.
##
##    When removing, the above changes will be undone.
##
## SYNTAX:    
##    cl_filenet_was_AE_CE_import -a -t 'HTTPSERVER' -h HttpServerName -p PrimaryNode -n SeondaryNodes -s ServiceIP \n\
##    cl_filenet_was_AE_CE_import -a -t 'APPSERVER' -c CellName -N WebSphereNode -p PrimaryNode -n SeondaryNodes -C Component -s ServiceIP \n\
##    cl_filenet_was_AE_CE_import -a -t 'DMMANAGER' -c CellName -p PrimaryNode -n SeondaryNodes -s ServiceIP\n\
##    cl_filenet_was_AE_CE_import -r -t 'HTTPSERVER' -h HttpServerName \n\
##    cl_filenet_was_AE_CE_import -r -t 'APPSERVER' -c CellName -N WebSphereNode \n\
##    cl_filenet_was_AE_CE_import -r -t 'DMMANAGER' -c CellName 
##
## EXIT CODES:    
##    0 - success
##    1 - failure
##
## KLIB Functions:
##    KLIB_AIX_ODM_get_odm_fields
##    KLIB_SA_get_metadata
##    KLIB_SA_delete_by_key_type_metadata
##    KLIB_HACMP_get_net_with_most_interfaces
##    KLIB_HACMP_generate_name
##    KLIB_SA_add_metadata
##
###################################################################

###############################################################################
#
# Name: usage
#
# Prints usage message and exits the program.
#
# Arguments:  none
#
# Returns:    does not return
#
################################################################################
function usage {
    set +u
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
    set -u

    dspmsg -s 10 filenetsa.cat 1 "Usage:\ncl_filenet_was_AE_CE_import -a -t 'HTTPSERVER' -C Component \n\
      -h HttpServerName -p PrimaryNode -n SeondaryNodes -s ServiceIP \n\
      cl_filenet_was_AE_CE_import -a -t 'APPSERVER' -c CellName -N WebSphereNode -C Component -p PrimaryNode -n SeondaryNodes -s ServiceIP \n\
      cl_filenet_was_AE_CE_import -a -t 'DMMANAGER' -c CellName -p PrimaryNode -n SeondaryNodes -s ServiceIP\n\
      cl_filenet_was_AE_CE_import -r -t 'HTTPSERVER' -h HttpServerName \n\
      cl_filenet_was_AE_CE_import -r -t 'APPSERVER' -c CellName -N WebSphereNode \n\
      cl_filenet_was_AE_CE_import -r -t 'DMMANAGER' -c CellName \n"

    exit 1
}


###############################################################################
#
# Name: UpdateResources
#
# Updates (-m) HACMP resources for Websphere Smart Assist added by
# AddResources.
#
# Syntax:
#       UpdateWASConfig
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################
function UpdateResources {

    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
    AE_CE=0

    if [[ -z $APPLICATION_NAME ]] ; then
        return 1
    fi
    
    typeset SERVICE_IP_LABEL_CHANGE=false
    typeset serviceip=""
    
    #############################################
    # Check the resource group exists or not, is offline, then remove it.
    #############################################
    typeset RESOURCE_GROUP
    [[ "$COMPONENT_ID" == "FILENET_CONTENT_ENGINE" ]] && {
        RESOURCE_GROUP=$(clodmget -q "name=CONTENT_ENGINE_RESOURCE_GROUP" \
-f value -d "=" HACMPsa_metadata)
	RESOURCE_GROUP=${RESOURCE_GROUP//\"/}

        [[ -z "$RESOURCE_GROUP" ]] && {
                RESOURCE_GROUP=$(clodmget -q "name=FILENET_AE_CE_RESOURCE_GROUP" \
-f value -d "=" HACMPsa_metadata)
		RESOURCE_GROUP=${RESOURCE_GROUP//\"/}
                AE_CE=1
        }
    }

    [[ "$COMPONENT_ID" == "FILENET_APPLICATION_ENGINE" ]] && {
        RESOURCE_GROUP=$(clodmget -q "name=APPLICATION_ENGINE_RESOURCE_GROUP" \
-f value -d "=" HACMPsa_metadata)
	RESOURCE_GROUP=${RESOURCE_GROUP//\"/}

        [[ -z "$RESOURCE_GROUP" ]] && {
                RESOURCE_GROUP=$(clodmget -q "name=FILENET_AE_CE_RESOURCE_GROUP" \
-f value -d "=" HACMPsa_metadata)
		RESOURCE_GROUP=${RESOURCE_GROUP//\"/}
                AE_CE=1
        }
    }
	
    if [[ -z $RESOURCE_GROUP ]]; then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 80 "WARNING: The Resource Group does not exist in HACMP.\n"
        RESOURCE_GROUP=$(KLIB_HACMP_generate_name "${APPLICATION_NAME}" 31 "_rg" "HACMPgroup" "group")
    else
        serviceip=$(KLIB_AIX_ODM_get_odm_fields "group=$RESOURCE_GROUP and name=SERVICE_LABEL" "HACMPresource" "value")

        if [[ $SERVICE_IP_LABEL != $serviceip ]] ; then
            SERVICE_IP_LABEL_CHANGE=true;
        fi
        
        dspmsg -s $IMPORT_MSGSET $WASSACAT 120 "Removing the resource group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
        
        # Is resource group online?
        typeset STATE=""
        set -a
            eval $(LC_ALL=C clvt query resource_group $RESOURCE_GROUP | grep "STATE=")
        set +a
        
        if [[ -n $STATE && $STATE != "OFFLINE" && $STATE != "ERROR" && $STATE != "UNKNOWN" ]] ; then
            # Resource group is not offline, error, or in unknown so exit
            dspmsg -s $IMPORT_MSGSET $WASSACAT 590 "Resource Group $RESOURCE_GROUP is still online.  It must me offline \n\
       before removing the WebSphere Component.\n" "$RESOURCE_GROUP"
            return 1
        fi
        
	#
        # Removing the depedency, if any with
        # the RG we are going to remove.
        # We can't remove the RG, without removing
        # any dependency exists with the RG.
        #
        clvt delete dependency RG=$RESOURCE_GROUP 1>/dev/null 2>&1

        clrmgrp -g $RESOURCE_GROUP
        if (( $? != 0 )); then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 130 "ERROR: Failed removing resource group $RESOURCE_GROUP from HACMP.\n" $RESOURCE_GROUP
            return 1
        fi
        
	if (( $AE_CE == 1 )); then
                clrmsaapp -a $APPLICATION_NAME FILENET_AE_CE_RESOURCE_GROUP
        else
                if [[ "$COMPONENT_ID" == "FILENET_APPLICATION_ENGINE" ]]; then
                        clrmsaapp -a $APPLICATION_NAME APPLICATION_ENGINE_RESOURCE_GROUP
                else
                        clrmsaapp -a $APPLICATION_NAME CONTENT_ENGINE_RESOURCE_GROUP
                fi
        fi
    fi
    
    #############################################
    # Check for new service label
    #############################################
    if [[ $SERVICE_IP_LABEL_CHANGE == true ]] ; then
        # create new one
        dspmsg -s $IMPORT_MSGSET $WASSACAT 140 "Creating service label ${SERVICE_IP_LABEL}.\n" ${SERVICE_IP_LABEL}
        NETWORK=$(KLIB_HACMP_get_net_with_most_interfaces $SERVICE_IP_LABEL)
        [[ -z $NETWORK || $? != 0 ]] && dspmsg -s $IMPORT_MSGSET $WASSACAT 150 " ERROR: Finding useable network.\n"
        
        claddnode -Tservice -B"$SERVICE_IP_LABEL" -w"$NETWORK"
        if (( $? != 0 )); then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 160 "ERROR: Failed creating HACMP Service IP Label $SERVICE_IP_LABEL.\n" $SERVICE_IP_LABEL
            return 1
        fi
    
        # delete old one
        for serviceIP in $serviceip; do
            clvt delete service_ip $serviceIP >/dev/null 2>&1
        done
    fi
    
    #############################################
    # Re-create resource group
    #############################################
    dspmsg -s $IMPORT_MSGSET $WASSACAT 180 "Creating HACMP Resource Group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
    
    typeset INSTALL_VGS=""
    typeset INSTALL_PATH=""
    typeset INSTALL_NODE_NAME=""
    typeset COMPONENT_ID=""
    typeset HACMP_SERVER_NAME=""
    typeset INSTALL_VGS=""
    set -a
        eval $(clquerysaapp -a $APPLICATION_NAME INSTALL_VGS)
        eval $(clquerysaapp -a $APPLICATION_NAME INSTALL_PATH)
        eval $(clquerysaapp -a $APPLICATION_NAME INSTALL_NODE_NAME)
        eval $(clquerysaapp -a $APPLICATION_NAME COMPONENT_ID)
        eval $(clquerysaapp -a $APPLICATION_NAME HACMP_SERVER_NAME)
        eval $(clquerysaapp -a $APPLICATION_NAME INSTALL_VGS)
    set +a
    
    if (( $AE_CE == 1 )); then
        RG=FILENET_AE_CE_RESOURCE_GROUP
    else
        if [[ "$COMPONENT_ID" == "FILENET_APPLICATION_ENGINE" ]]; then
                RG=APPLICATION_ENGINE_RESOURCE_GROUP
        else
                RG=CONTENT_ENGINE_RESOURCE_GROUP
        fi
    fi

    claddsaapp -a $APPLICATION_NAME $RG="${RESOURCE_GROUP}"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "RESOURCE_GROUP" ${RESOURCE_GROUP}
        return 1
    fi
    
    claddgrp -g "$RESOURCE_GROUP" -s "ignore" -n "$PRIMARY $SECONDARY" -S 'OHN' -O 'FNPN' -B 'NFB' -A $COMPONENT_ID -K $APPLICATION_NAME
    if (( $? != 0 )); then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 190 "ERROR: Failed creating HACMP Resource Group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
        return 1
    fi

    claddres -g "$RESOURCE_GROUP" SERVICE_LABEL="$SERVICE_IP_LABEL" APPLICATIONS="$HACMP_SERVER_NAME" \
    VOLUME_GROUP="$INSTALL_VGS" FORCED_VARYON='false' \
    VG_AUTO_IMPORT='true' FILESYSTEM= FSCHECK_TOOL='fsck' \
    RECOVERY_METHOD='parallel' FS_BEFORE_IPADDR='false' \
    EXPORT_FILESYSTEM=  \
    MOUNT_FILESYSTEM= NFS_NETWORK= \
    SHARED_TAPE_RESOURCES= DISK= AIX_FAST_CONNECT_SERVICES= \
    COMMUNICATION_LINKS= MISC_DATA=

    if (( $? != 0 )); then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 200 "ERROR: Failed updating HACMP Resource Group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
        return 1
    fi

    # If Service IP Label changed 
    if [[ $SERVICE_IP_LABEL_CHANGE == true ]] ; then
    
        # Update WAS/IHS Config
        if [[ "$COMPONENT_TYPE" == "HTTPSERVER" ]]; then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 660 "Setting Listen Directive for IBM Http Server on node $INSTALL_NODE_NAME to the value \"$SERVICE_IP_LABEL\".\n" $INSTALL_NODE_NAME $SERVICE_IP_LABEL
            cl_rsh $INSTALL_NODE_NAME "$WASSA_SBIN_DIR/cl_wasconfigihs $INSTALL_VGS $INSTALL_PATH $SERVICE_IP_LABEL" >/dev/null
            if (( $? != 0 )) ; then
                dspmsg -s $IMPORT_MSGSET $WASSACAT 680 "ERROR: Failed setting Listen Directive for IBM Http Server on node %s." $INSTALL_NODE_NAME 
                return 1
            fi
        fi

        if [[ "$COMPONENT_TYPE" == "APPSERVER" || "$COMPONENT_TYPE" == "DMMANAGER" ]]; then
            typeset PROFILE_NAME=""
            typeset WAS_SERVER_NAME=""
            typeset ENDPOINT_HOST=""
            typeset WAS_CELL_NAME=""
            typeset WAS_NODE_NAME=""
            set -a
                eval $(clquerysaapp -a $APPLICATION_NAME PROFILE_NAME)
                eval $(clquerysaapp -a $APPLICATION_NAME WAS_SERVER_NAME)
                eval $(clquerysaapp -a $APPLICATION_NAME ENDPOINT_HOST)
                eval $(clquerysaapp -a $APPLICATION_NAME WAS_CELL_NAME)
                eval $(clquerysaapp -a $APPLICATION_NAME WAS_NODE_NAME)
            set +a

            WAS_SERVER_NAME=$(echo $WAS_SERVER_NAME | cut -f 1 -d' ')
            
            typeset type=""
            typeset server_name

            if [[ "$COMPONENT_TYPE" == "APPSERVER" ]] ; then
                type="WebSphere Application Server"
            else
                type="Deployment Manager"
            fi

            for server_name in $WAS_SERVER_NAME; do
                dspmsg -s $IMPORT_MSGSET $WASSACAT 670 "Setting End Point host for $type on $INSTALL_NODE_NAME for \n\
                       WebSphere Cell $CELL, Node $WEBSPHERE_NODE, Server $server_name to the value \"${SERVICE_IP_LABEL}\".\n" "$type" "$INSTALL_NODE_NAME" "$CELL" "$WEBSPHERE_NODE" "$server_name" "$SERVICE_IP_LABEL"
                cl_rsh $INSTALL_NODE_NAME "$WASSA_SBIN_DIR/cl_wasconfigserver $INSTALL_VGS $INSTALL_PATH $PROFILE_NAME $WAS_CELL_NAME $WAS_NODE_NAME $server_name $SERVICE_IP_LABEL" >/dev/null
                if (( $? != 0 )) ; then
                    dspmsg -s $IMPORT_MSGSET $WASSACAT 690 "ERROR: Failed setting End Point host for $type on $INSTALL_NODE_NAME for \n\
                           WebSphere Cell $CELL, Node $WEBSPHERE_NODE, Server $server_name."  "$type" "$INSTALL_NODE_NAME" "$CELL" "$WEBSPHERE_NODE" "$server_name"
                    return 1
                fi
            done
        fi

        # Remove old HACMPsa_metadata entry for service label
        clrmsaapp -a $APPLICATION_NAME SERVICE_IP_LABEL
        
        # Add new HACMPsa_metadata entry for service label
        claddsaapp -a $APPLICATION_NAME SERVICE_IP_LABEL="${SERVICE_IP_LABEL}"
        if (( $? != 0 )); then
            dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "SERVICE_IP_LABEL" ${SERVICE_IP_LABEL}
            return 1
        fi
    fi

    return 0
}



###############################################################################
#
# Name: ResetWASConfig
#
# Removes (-r) HACMP resources for Websphere Smart Assist added by
# AddResources.
#
# Syntax:
#       ResetWASConfig
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################
function ResetWASConfig {

    set +u
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
    set -u

    typeset INSTALL_VGS=""
    typeset INSTALL_PATH=""
    typeset INSTALL_NODE_NAME
    set -a
        eval $(clquerysaapp -a $APPLICATION_NAME INSTALL_VGS)
        eval $(clquerysaapp -a $APPLICATION_NAME INSTALL_PATH)
        eval $(clquerysaapp -a $APPLICATION_NAME INSTALL_NODE_NAME)
    set +a

    if [[ "$COMPONENT_TYPE" == "HTTPSERVER" ]]; then
        typeset LISTEN_HOST=""
        set -a
            eval $(clquerysaapp -a $APPLICATION_NAME LISTEN_HOST)
        set +a


        dspmsg -s $IMPORT_MSGSET $WASSACAT 660 "Setting Listen Directive for IBM Http Server on node $INSTALL_NODE_NAME to the value \"$LISTEN_HOST\".\n" "$INSTALL_NODE_NAME" "$LISTEN_HOST"
        cl_rsh $INSTALL_NODE_NAME "$WASSA_SBIN_DIR/cl_wasconfigihs $INSTALL_VGS $INSTALL_PATH $LISTEN_HOST" >/dev/null
        if (( $? != 0 )) ; then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 680 "ERROR: Failed setting Listen Directive for IBM Http Server on node %s." $INSTALL_NODE_NAME 
            return 1
        fi
    fi

    if [[ "$COMPONENT_TYPE" == "APPSERVER" || "$COMPONENT_TYPE" == "DMMANAGER" ]]; then
        typeset PROFILE_NAME=""
        typeset WAS_SERVER_NAME=""
        typeset ENDPOINT_HOST=""
        typeset WAS_CELL_NAME=""
        typeset WAS_NODE_NAME=""
        set -a
            eval $(clquerysaapp -a $APPLICATION_NAME PROFILE_NAME)
            eval $(clquerysaapp -a $APPLICATION_NAME WAS_SERVER_NAME)
            eval $(clquerysaapp -a $APPLICATION_NAME ENDPOINT_HOST)
            eval $(clquerysaapp -a $APPLICATION_NAME WAS_CELL_NAME)
            eval $(clquerysaapp -a $APPLICATION_NAME WAS_NODE_NAME)
        set +a

        WAS_SERVER_NAME=$(echo $WAS_SERVER_NAME | cut -f 1 -d' ')

        typeset type=""
        typeset server_name=""

        if [[ "$COMPONENT_TYPE" == "APPSERVER" ]] ; then
            type="WebSphere Application Server"
        else
            type="Deployment Manager"
        fi

        for server_name in $WAS_SERVER_NAME; do
            dspmsg -s $IMPORT_MSGSET $WASSACAT 670 "Setting End Point host for $type on $INSTALL_NODE_NAME for \n\
   WebSphere Cell $WAS_CELL_NAME, Node $WAS_NODE_NAME, Server $server_name to the value \"${ENDPOINT_HOST}\".\n" "$type" "$INSTALL_NODE_NAME" "$WAS_CELL_NAME" "$WAS_NODE_NAME" "$server_name" "$ENDPOINT_HOST"
            cl_rsh $INSTALL_NODE_NAME "$WASSA_SBIN_DIR/cl_wasconfigserver $INSTALL_VGS $INSTALL_PATH $PROFILE_NAME $WAS_CELL_NAME $WAS_NODE_NAME $server_name $ENDPOINT_HOST" >/dev/null
            if (( $? != 0 )) ; then
                dspmsg -s $IMPORT_MSGSET $WASSACAT 690 "ERROR: Failed setting End Point host for $type on $INSTALL_NODE_NAME for \n\
   WebSphere Cell $WAS_CELL_NAME, Node $WAS_NODE_NAME, Server $server_name."  "$type" "$INSTALL_NODE_NAME" "$WAS_CELL_NAME" "$WAS_NODE_NAME" "$server_name"
                return 1
            fi
        done
    fi

    return 0

}


###############################################################################
#
# Name: RemoveHACMPResources
#
# Removes (-r) HACMP resources for Websphere Smart Assist added by
# AddResources.
#
# Syntax:
#       RemoveHACMPResources
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################
RemoveHACMPResources() {

    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
    
    # If we are here, then something happened during import, so 
    # all the values that are in HACMPsa_metadata should be correct

    ERROR=0
    

    # Check the resource group exists or not.
    typeset RESOURCE_GROUP
	set -a
	    eval $(clquerysaapp -a $APPLICATION_NAME RESOURCE_GROUP)
	set +a
    if [[ -z $RESOURCE_GROUP ]]; then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 80 "WARNING: The Resource Group does not exist in HACMP.\n"
    return 0
    fi


    # Remove Application Server from the HACMP.
    typeset HACMP_SERVER_NAME
	set -a
	    eval $(clquerysaapp -a $APPLICATION_NAME HACMP_SERVER_NAME)
	set +a

    if [[ -n $HACMP_SERVER_NAME ]]; then

        cllsserv -n $HACMP_SERVER_NAME > /dev/null 2>&1
        if (( $? == 0 )); then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 440 "Removing HACMP Application Server $HACMP_SERVER_NAME from HACMP.\n" $HACMP_SERVER_NAME
            clrmserv "$HACMP_SERVER_NAME" 
            if (( $? != 0 )); then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 450 "ERROR: Failed removing HACMP Application Server $HACMP_SERVER_NAME from HACMP.\n" $HACMP_SERVER_NAME
            ERROR=1
            fi
        else
            dspmsg -s $IMPORT_MSGSET $WASSACAT 460 "WARNING: The HACMP Application Server $HACMP_SERVER_NAME does not exist in HACMP.\n" $HACMP_SERVER_NAME
        fi
    else
        dspmsg -s $IMPORT_MSGSET $WASSACAT 470 "WARNING: The HACMP Application Server does not exist in HACMPsa_metadata.\n"
    fi
   
   
    # Remove Application Monitor
    typeset HACMP_MONITOR_NAME
	set -a
	    eval $(clquerysaapp -a $APPLICATION_NAME HACMP_MONITOR_NAME)
	set +a
    if [[ -n $HACMP_MONITOR_NAME ]] ; then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 480 "Removing HACMP Application Monitor $HACMP_MONITOR_NAME from HACMP.\n" $HACMP_MONITOR_NAME
        clrmappmon $HACMP_MONITOR_NAME > /dev/null 2>&1
        if (( $? != 0 )); then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 490 "ERROR: Failed removing HACMP Application Monitor $HACMP_MONITOR_NAME from HACMP.\n" $HACMP_MONITOR_NAME
            ERROR=1
        fi
    fi


    # Remove Service IP Label from the HACMP.
    typeset SERVICE_IP_LABEL
	set -a
	    eval $(clquerysaapp -a $APPLICATION_NAME SERVICE_IP_LABEL)
	set +a
    if [[ -n $SERVICE_IP_LABEL ]]; then
    dspmsg -s $IMPORT_MSGSET $WASSACAT 90 "Removing Service IP Label $SERVICE_IP_LABEL from HACMP.\n" $SERVICE_IP_LABEL
        clrmnode -a "$SERVICE_IP_LABEL"
        if (( $? != 0 )); then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 100 "ERROR: Failed removing Service IP Label $SERVICE_IP_LABEL from HACMP.\n" $SERVICE_IP_LABEL
            ERROR=1
        fi
    else
        dspmsg -s $IMPORT_MSGSET $WASSACAT 110 "WARNING: The Service IP Label does not exist in HACMPsa_metadata ODM.\n"
    fi

   # Remove Resource Group from the HACMP.
    if [[ -n $RESOURCE_GROUP ]]; then
    dspmsg -s $IMPORT_MSGSET $WASSACAT 120 "Removing the resource group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
        clrmgrp -g $RESOURCE_GROUP
        if (( $? != 0 )); then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 130 "ERROR: Failed removing resource group $RESOURCE_GROUP from HACMP.\n" $RESOURCE_GROUP
            ERROR=1
        fi
    fi

    return $ERROR
}


###############################################################################
#
# Name: AddResources
#
# Adds (-a) HACMP resources for Websphere Smart Assist.  If the resources already exist,
# they will be removed and then added.  Entries will also be added to the
# HACMPsa_metadata ODM.  
#
# Syntax:
#       AddResources
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################
AddResources() {

    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x

    # find the information related to the selected HTTP Server
    if [[ "$COMPONENT_TYPE" == "HTTPSERVER" ]]; then 
        cl_rsh $HTTPSERVER $WASSA_SBIN_DIR/cl_wasdiscihs 2>/dev/null | while read line; do
            echo $line | IFS=: read component install_count INSTALL_PATH version INSTALL_VGS install_pvids LISTEN_HOST
            
            # Only read one line because that's all there should be
            # Perform no checks because those have already been done
            break;
        done
        
        INSTALL_NODE_NAME=$HTTPSERVER
        
        STARTSCRIPT="cl_wasihsstart"
        STOPSCRIPT="cl_wasihsstop"
        MONSCRIPT="cl_wasihsmon"

    else
        # Use the Discovery file
        if [[ -r $WASSA_DISC_FILE ]]; then
            # source the discovery file.
	        . $WASSA_DISC_FILE    
        else
	        # error
	        dspmsg -s $CONF_MSGSET $WASSACAT 500 "Could not find WebSphere discovery file.  Please run WebSphere Discovery.\n"
	        exit 1; 
        fi
        
        if [[ "$COMPONENT_TYPE" == "APPSERVER" ]]; then 
            typeset -n instance=$INSTANCE_KEY
            if [[ -n ${instance[INSTALL_NODE_NAME]} ]]; then
                INSTALL_NODE_NAME=${instance[INSTALL_NODE_NAME]}
                INSTALL_PATH=${instance[INSTALL_PATH]}
                INSTALL_VGS=${instance[INSTALL_VGS]}
                INSTALL_VGS=$(echo $INSTALL_VGS | sed 's/^[ \t]*//')
                ISMANAGED=${instance[IS_MANAGED]}
                WAS_SERVER_NAME=${instance[WAS_SERVER_NAME]}
                WAS_CELL_NAME=${instance[WAS_CELL_NAME]}
                WAS_NODE_NAME=${instance[WAS_NODE_NAME]}
                PROFILE_NAME=${instance[PROFILE_NAME]}
                ENDPOINT_HOST=${instance[ENDPOINT_HOST]}


                STARTSCRIPT="cl_wasnodestart"
                STOPSCRIPT="cl_wasnodestop"
                MONSCRIPT="cl_wasnodemon"
            else
                # error
                dspmsg -s $IMPORT_MSGSET $WASSACAT 520 "Discovery file doesn't have information regarding the specified Websphere Application Server Node $WEBSPHERE_NODE on WebSphere Cell ${CELL}.\n" $WEBSPHERE_NODE ${CELL}
            fi
        elif [[ "$COMPONENT_TYPE" == "DMMANAGER" ]]; then 
            typeset -n instance=$INSTANCE_KEY
            if [[ -n ${instance[INSTALL_NODE_NAME]} ]] ; then
                INSTALL_NODE_NAME=${instance[INSTALL_NODE_NAME]}
                INSTALL_PATH=${instance[INSTALL_PATH]}
                INSTALL_VGS=${instance[INSTALL_VGS]}
                WAS_SERVER_NAME=${instance[WAS_SERVER_NAME]}
                WAS_CELL_NAME=${instance[WAS_CELL_NAME]}
                WAS_NODE_NAME=${instance[WAS_NODE_NAME]}
                PROFILE_NAME=${instance[PROFILE_NAME]}
                ENDPOINT_HOST=${instance[ENDPOINT_HOST]}

                STARTSCRIPT="cl_wasdmstart"
                STOPSCRIPT="cl_wasdmstop"
                MONSCRIPT="cl_wasdmmon"
            else
                dspmsg -s $IMPORT_MSGSET $WASSACAT 530 "Discovery file doesn't have information regarding Deployment Manager for WebSphere Cell ${CELL}.\n" ${CELL}
            fi
        fi
    fi
    
	# Add an entry into the HACMPsa_metadata ODM for the application id
	# and SMARTASSIST_ID and COMPONENT_ID
	claddsaapp -a "$APPLICATION_NAME" SMARTASSIST_ID='FILENET' \
COMPONENT_ID="$COMPONENT_ID" APPLICATION_NAME="$APPLICATION_NAME" INSTANCE_NAME="$INSTANCE_KEY"


    # Create the Service IP Label
    # Find a useable network for this service IP label, this
    # is the same method used by the 2 node configuration assistant

    dspmsg -s $IMPORT_MSGSET $WASSACAT 140 "Creating service label ${SERVICE_IP_LABEL}.\n" ${SERVICE_IP_LABEL}
    NETWORK=$(KLIB_HACMP_get_net_with_most_interfaces $SERVICE_IP_LABEL)
    [[ -z $NETWORK || $? != 0 ]] && dspmsg -s $IMPORT_MSGSET $WASSACAT 150 " ERROR: Finding useable network.\n"
    
    claddsaapp -a $APPLICATION_NAME SERVICE_IP_LABEL="${SERVICE_IP_LABEL}"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "SERVICE_IP_LABEL" ${SERVICE_IP_LABEL}
        return 1
    fi

    KLIB_SA_add_ServiceLabel $SERVICE_IP_LABEL $NETMASK_PREFIX_LEN
    if (( $? != 0 )); then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 160 "ERROR: Failed creating HACMP Service IP Label $SERVICE_IP_LABEL.\n" $SERVICE_IP_LABEL
        return 1
    fi
    

    # Create a HACMP application server   
    HACMP_SERVER_NAME=$(KLIB_HACMP_generate_name "${APPLICATION_NAME}" 31 "_as" "HACMPserver" "name")
    dspmsg -s $IMPORT_MSGSET $WASSACAT 540 "Creating HACMP Application Server $HACMP_SERVER_NAME.\n" $HACMP_SERVER_NAME

    claddsaapp -a $APPLICATION_NAME HACMP_SERVER_NAME="${HACMP_SERVER_NAME}"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "HACMP_SERVER_NAME" ${HACMP_SERVER_NAME}
        return 1
    fi

    claddserv -s "$HACMP_SERVER_NAME" \
    -b "${WASSA_SBIN_DIR}/$STARTSCRIPT $APPLICATION_NAME" \
    -e "${WASSA_SBIN_DIR}/$STOPSCRIPT $APPLICATION_NAME"

    if (( $? != 0 )); then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 550 "ERROR: Failed creating HACMP Application Server $HACMP_SERVER_NAME.\n" $HACMP_SERVER_NAME
        return 1
    fi


    # Create the Application Monitor
    HACMP_MONITOR_NAME=$(KLIB_HACMP_generate_name "${APPLICATION_NAME}" 32 "_monitor" "HACMPmonitor" "monitor")
    claddsaapp -a $APPLICATION_NAME HACMP_MONITOR_NAME="${HACMP_MONITOR_NAME}"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "HACMP_MONITOR_NAME" ${HACMP_MONITOR_NAME}
        return 1
    fi

    dspmsg -s $IMPORT_MSGSET $WASSACAT 570 "Creating HACMP Custom Application Monitor $HACMP_MONITOR_NAME.\n " $HACMP_MONITOR_NAME
    claddappmon MONITOR_TYPE=user name=$HACMP_MONITOR_NAME \
                RESOURCE_TO_MONITOR=$HACMP_SERVER_NAME \
                MONITOR_METHOD="${WASSA_SBIN_DIR}/${MONSCRIPT} ${APPLICATION_NAME}" \
                INVOCATION='longrunning' \
                MONITOR_INTERVAL='120' STABILIZATION_INTERVAL='420' \
                RESTART_COUNT='3' RESTART_INTERVAL='1800' FAILURE_ACTION='fallover' \
                CLEANUP_METHOD="${WASSA_SBIN_DIR}/$STOPSCRIPT $APPLICATION_NAME" \
                RESTART_METHOD="${WASSA_SBIN_DIR}/$STARTSCRIPT $APPLICATION_NAME" \
                HUNG_MONITOR_SIGNAL='9' > /dev/null 2>&1
    if (( $? != 0 )); then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 580 "ERROR: Failed creating HACMP Custom Application Monitor $HACMP_MONITOR_NAME.\n" $HACMP_MONITOR_NAME
        return 1
    fi


    # Create the Resource Group
    RESOURCE_GROUP=$(KLIB_HACMP_generate_name "${APPLICATION_NAME}" 31 "_rg" "HACMPgroup" "group")
    dspmsg -s $IMPORT_MSGSET $WASSACAT 180 "Creating HACMP Resource Group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
    VG_LIST=""
    [[ "$COMPONENT_ID" == "FILENET_CONTENT_ENGINE" ]] && {
        [[ -n $CE_INSTALL_PATH ]] && {
                KLIB_AIX_add_vg_by_path VG_LIST $CE_INSTALL_PATH "$INSTALL_VGS"
        }
        claddsaapp -a $APPLICATION_NAME CONTENT_ENGINE_RESOURCE_GROUP="${RESOURCE_GROUP}"
        if (( $? != 0 )); then
                dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "RESOURCE_GROUP" ${RESOURCE_GROUP}
                return 1
        fi
    }
    [[ "$COMPONENT_ID" == "FILENET_APPLICATION_ENGINE" ]] && {
        [[ -n $AE_INSTALL_PATH ]] && {
                KLIB_AIX_add_vg_by_path VG_LIST $AE_INSTALL_PATH "$INSTALL_VGS"
        }

        claddsaapp -a $APPLICATION_NAME APPLICATION_ENGINE_RESOURCE_GROUP="${RESOURCE_GROUP}"
        if (( $? != 0 )); then
                dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "RESOURCE_GROUP" ${RESOURCE_GROUP}
                return 1
        fi
    }
    
    claddgrp -g "$RESOURCE_GROUP" -s "ignore" -n "$PRIMARY $SECONDARY" -S 'OHN' -O 'FNPN' -B 'NFB' -A $COMPONENT_ID -K $APPLICATION_NAME
    if (( $? != 0 )); then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 190 "ERROR: Failed creating HACMP Resource Group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
        return 1
    fi

    [[ -n "$VG_LIST" ]] && {
        KLIB_UTIL_LIST_unique_key_list VG_LIST "$INSTALL_VGS $VG_LIST"
    }

    [[ -z "$VG_LIST" ]] && {
        KLIB_UTIL_LIST_unique_key_list VG_LIST "$INSTALL_VGS"
    }

    claddres -g "$RESOURCE_GROUP" SERVICE_LABEL="$SERVICE_IP_LABEL" APPLICATIONS="$HACMP_SERVER_NAME" \
    VOLUME_GROUP="$VG_LIST" FORCED_VARYON='false' \
    VG_AUTO_IMPORT='true' FILESYSTEM= FSCHECK_TOOL='fsck' \
    RECOVERY_METHOD='parallel' FS_BEFORE_IPADDR='false' \
    EXPORT_FILESYSTEM=  \
    MOUNT_FILESYSTEM= NFS_NETWORK= \
    SHARED_TAPE_RESOURCES= DISK= AIX_FAST_CONNECT_SERVICES= \
    COMMUNICATION_LINKS= MISC_DATA=

    if (( $? != 0 )); then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 200 "ERROR: Failed updating HACMP Resource Group $RESOURCE_GROUP.\n" $RESOURCE_GROUP
        return 1
    fi

    ###############################################################
    # Update WebSphere Component Configuration
    ###############################################################

    if [[ "$COMPONENT_TYPE" == "HTTPSERVER" ]]; then
        dspmsg -s $IMPORT_MSGSET $WASSACAT 660 "Setting Listen Directive for IBM Http Server on node $INSTALL_NODE_NAME to the value \"$SERVICE_IP_LABEL\".\n" $INSTALL_NODE_NAME $SERVICE_IP_LABEL
        cl_rsh $INSTALL_NODE_NAME "$WASSA_SBIN_DIR/cl_wasconfigihs $INSTALL_VGS $INSTALL_PATH $SERVICE_IP_LABEL" >/dev/null
        if (( $? != 0 )) ; then
            dspmsg -s $IMPORT_MSGSET $WASSACAT 680 "ERROR: Failed setting Listen Directive for IBM Http Server on node %s." $INSTALL_NODE_NAME 
            return 1
        fi
    fi

    if [[ "$COMPONENT_TYPE" == "APPSERVER" || "$COMPONENT_TYPE" == "DMMANAGER" ]]; then
        typeset type=""
        typeset server_name

        if [[ "$COMPONENT_TYPE" == "APPSERVER" ]] ; then
            type="WebSphere Application Server"
        else
            type="Deployment Manager"
        fi

        for server_name in $WAS_SERVER_NAME; do
            dspmsg -s $IMPORT_MSGSET $WASSACAT 670 "Setting End Point host for $type on $INSTALL_NODE_NAME for \n\
   WebSphere Cell $CELL, Node $WEBSPHERE_NODE, Server $server_name to the value \"${SERVICE_IP_LABEL}\".\n" "$type" "$INSTALL_NODE_NAME" "$CELL" "$WEBSPHERE_NODE" "$server_name" "$SERVICE_IP_LABEL"
            cl_rsh $INSTALL_NODE_NAME "$WASSA_SBIN_DIR/cl_wasconfigserver $INSTALL_VGS $INSTALL_PATH $PROFILE_NAME $WAS_CELL_NAME $WAS_NODE_NAME $server_name $SERVICE_IP_LABEL" >/dev/null
            if (( $? != 0 )) ; then
                dspmsg -s $IMPORT_MSGSET $WASSACAT 690 "ERROR: Failed setting End Point host for $type on $INSTALL_NODE_NAME for \n\
   WebSphere Cell $CELL, Node $WEBSPHERE_NODE, Server $server_name."  "$type" "$INSTALL_NODE_NAME" "$CELL" "$WEBSPHERE_NODE" "$server_name"
                return 1
            fi
        done
    fi



    # add the metadata common elements
    AddCommonresources
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 410 "ERROR: Failed updating HACMPsa_metadata ODM.\n"
    return 1
    fi
    if [[ "$COMPONENT_TYPE" == "HTTPSERVER" ]]; then
        # add the metadata elments specific to HTTP resources
        AddHTTPresources
    elif [[ "$COMPONENT_TYPE" == "APPSERVER" ]]; then
        # add the metadata elments specific to Websphere Application Server Node resources.
        AddNoderesources
    elif [[ "$COMPONENT_TYPE" == "DMMANAGER" ]]; then
        # add the metadata elments specific to Websphere Application Server Node resources.
        AddDMresources
    fi
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 410 "ERROR: Failed updating HACMPsa_metadata odm"
        return 1
    fi

    #
    # Establish dependencies across
    #  	application engine RG
    #   content engine RG
    #   DB for application engine RG
    #   DB for content engine RG
    #   process engine RG,
    # if above RGs are available.
    #
    AE_CE_RG=$(clodmget -q "name=FILENET_AE_CE_RESOURCE_GROUP" -f value -d"=" HACMPsa_metadata)
    AE_CE_RG=${AE_CE_RG//\"/}
    [[ -z $AE_CE_RG ]] && {
	AE_RG=$(clodmget -q "name=APPLICATION_ENGINE_RESOURCE_GROUP" -f value -d "=" HACMPsa_metadata)
	AE_RG=${AE_RG//\"/}
	CE_RG=$(clodmget -q "name=CONTENT_ENGINE_RESOURCE_GROUP" -f value -d "=" HACMPsa_metadata)
	CE_RG=${CE_RG//\"/}
    }
    DB_RG=$(clodmget -q "name=FILENET_DB_PE_CE_RESOURCE_GROUP" -f value -d "=" HACMPsa_metadata)
    DB_RG=${DB_RG//\"/}
    [[ -z $DB_RG ]] && {
	DB_PE_RG=$(clodmget -q "name=FILENET_DB_PE_RESOURCE_GROUP" -f value -d "=" HACMPsa_metadata)
	DB_PE_RG=${DB_PE_RG//\"/}
	DB_CE_RG=$(clodmget -q "name=FILENET_DB_CE_RESOURCE_GROUP" -f value -d "=" HACMPsa_metadata)
	DB_CE_RG=${DB_CE_RG//\"/}
    }
    PE_RG=$(clodmget -q "name=PROCESS_ENGINE_RESOURCE_GROUP" -f value -d "=" HACMPsa_metadata)
    PE_RG=${PE_RG//\"/}

    [[ -n $AE_CE_RG ]] && {
	[[ -n $DB_RG ]] && {
		clrgdependency -t 'START_AFTER' -a -c "$AE_CE_RG" -p "$DB_RG"
	}
	[[ -n $DB_CE_RG ]] && {
		clrgdependency -t 'START_AFTER' -a -c "$AE_CE_RG" -p "$DB_CE_RG"
	}
	[[ -n $PE_RG ]] && {
		clrgdependency -t 'START_AFTER' -a -c "$PE_RG" -p "$AE_CE_RG"
	}
    }

    [[ -n $CE_RG ]] && {
	[[ -n $DB_CE_RG ]] && {
		clrgdependency -t 'START_AFTER' -a -c "$CE_RG" -p "$DB_CE_RG"
	}

	[[ -n $DB_RG ]] && {
		clrgdependency -t 'START_AFTER' -a -c "$CE_RG" -p "$DB_RG"
	}

	[[ -n $PE_RG && -n $AE_RG ]] && [[ -n $DB_RG || -n $DB_CE_RG ]] || {
		clrgdependency -t 'START_AFTER' -a -c "$PE_RG" -p "$CE_RG"
	}
	
	[[ -n $AE_RG ]] && {
		clrgdependency -t 'START_AFTER' -a -c "$AE_RG" -p "$CE_RG"
	}
    }

    [[ -n $AE_RG ]] && {
	[[ -n $PE_RG ]] && {
		[[ -n $CE_RG ]] && [[ -n $DB_RG || -n $DB_CE_RG ]] && {
			clrgdependency -t 'START_AFTER' -d -c "$PE_RG" -p "$CE_RG"
		}
		clrgdependency -t 'START_AFTER' -a -c "$AE_RG" -p "$PE_RG"
	}

	[[ -n $CE_RG ]] && {
		clrgdependency -t 'START_AFTER' -a -c "$AE_RG" -p "$CE_RG"
	}
    }

    return 0
}


###############################################################################
# Name: AddNodeResources
#
# Entries related to Websphere Application Server Node will be added 
# to the HACMPsa_metadata ODM.  
#
# Syntax:
#       AddNodeResources
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################

AddNoderesources() {
    
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x

    # A lot of sa_metadata addtions are the same sa deployment manager
    AddDMresources

    claddsaapp -a "$APPLICATION_NAME" IS_MANAGED="$ISMANAGED"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "IS_MANAGED" $ISMANAGED
        return 1
    fi

    return 0

}


###############################################################################
#
# Name: AddDMResources
#
# Entries related to Deployment Manager will be added 
# to the HACMPsa_metadata ODM.  
#
# Syntax:
#       AddDMResources
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################

AddDMresources() {
    
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x
    
    claddsaapp -a "$APPLICATION_NAME" WAS_CELL_NAME="$CELL"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "WAS_CELL_NAME" $CELL
        return 1
    fi

    claddsaapp -a "$APPLICATION_NAME" WAS_NODE_NAME="$WAS_NODE_NAME"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "WAS_NODE_NAME" $WAS_NODE_NAME
        return 1
    fi


    claddsaapp -a "$APPLICATION_NAME" WAS_SERVER_NAME="$WAS_SERVER_NAME"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "WAS_SERVER_NAME" $WAS_SERVER_NAME
        return 1
    fi

    claddsaapp -a "$APPLICATION_NAME" PROFILE_NAME="$PROFILE_NAME"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "PROFILE_NAME" $PROFILE_NAME
        return 1
    fi

    claddsaapp -a "$APPLICATION_NAME" ENDPOINT_HOST="$ENDPOINT_HOST"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "ENDPOINT_HOST" $ENDPOINT_HOST
        return 1
    fi

    return 0

}


###############################################################################
#
# Name: AddHTTPResources
#
# Entries related to HTTP Server will be added to the HACMPsa_metadata ODM.  
#
# Syntax:
#       AddHTTPResources
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################
AddHTTPresources() {
    
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x

    claddsaapp -a "$APPLICATION_NAME" LISTEN_HOST="$LISTEN_HOST"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "LISTEN_HOST" $LISTEN_HOST
        return 1
    fi


    return 0

}

###############################################################################
#
# Name: AddCommonResources
#
# Entries related to all the components (HTTP Server /Websphere Application 
# Server Node) will be added to the HACMPsa_metadata ODM.  
#
# Syntax:
#       AddCommonResources
# 
# Arguments: none
# 
# Global Variables:
#
# Returns:
#    0 on SUCCESS
#    1 on FAILURE
#
################################################################################

AddCommonresources() {
    
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x

    claddsaapp -a "$APPLICATION_NAME" INSTALL_NODE_NAME="$INSTALL_NODE_NAME"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "INSTALL_NODE_NAME" $INSTALL_NODE_NAME
        return 1
    fi

    claddsaapp -a "$APPLICATION_NAME" INSTALL_PATH="$INSTALL_PATH"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "INSTALL_PATH" $INSTALL_PATH
        return 1
    fi

    claddsaapp -a "$APPLICATION_NAME" INSTALL_VGS="$INSTALL_VGS"
    if (( $? != 0 )); then
        dspmsg -s $CONF_MSGSET $WASSACAT 390 "ERROR: Failed adding %1\$s %2\$s to the HACMPsa_metadata ODM.\n" "INSTALL_VGS" $INSTALL_VGS
        return 1
    fi

    return 0
}
################################################################################
#
# Name:         createDiscoveryFile
#
# Description:
#               This function will read the supplid config file and create HACMP
#               resources to configure WAS for HA.
#
# Arguments:
#		manual configuration type
#
# Returns:
#               exit with 1 on failure
#
################################################################################
createDiscoveryFile() {
	[[ "$VERBOSE_LOGGING" == "high" ]] && set -x

	MANUAL_CONFIG_TYPE=$1
        cell=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep CELL_NAME)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
             exit 1
        }
        WAS_CELL_NAME=$(echo $cell | cut -d"=" -f2)

        node=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep NODE_NAME)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
             exit 1
        }
        WAS_NODE_NAME=$(echo $node | cut -d"=" -f2)
	APPLICATION_NAME="WAS_NODE_${WAS_CELL_NAME}_${WAS_NODE_NAME}"

	# Look for already configured instances
        clquerysaapp -a $APPLICATION_NAME INSTALL_NODE_NAME > /dev/null 2>&1
        if (( $? == 0 )) ; then
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 2 "WebSphere Application Server with Cell \
Name %s and Node Name %s is already configured under powerHA" $WAS_CELL_NAME $WAS_NODE_NAME
            exit 0;
        fi

        server=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep SERVER_NAME)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
             exit 1
        }
        WAS_SERVER_NAME=$(echo $server | cut -d"=" -f2)
        primary_node=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep PrimaryNode)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            exit 1

        }
        primary_node=$(echo $primary_node | cut -d"=" -f2)
        found=0
        for node in `/usr/es/sbin/cluster/utilities/clnodename`
        do
            [[ $node == $primary_node ]] && {
                found=1
            }
        done
        (( $found == 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 3 "Primary Node %s is not valid in the cluster.\n" $primary_node
            exit 1
        }
        PRIMARY=$primary_node
        takover_nodes=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep TakeoverNodes)
        takover_nodes=$(echo $takover_nodes | cut -d"=" -f2)
        takeover_nodes=$(echo $takover_nodes  | tr ',' ' ')
        found=1
        for tnode in $takeover_nodes
        do
            flag=0
            for node in `/usr/es/sbin/cluster/utilities/clnodename`
            do
                [[ $node == $tnode ]] && {
                    flag=1
                }
            done
            (( $flag == 0 )) && {
                found=0
            }
        done

	(( $found == 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 4 "One of the Takeover node from %s is not valid in the cluster.\n" $takeover_nodes
        }

        SECONDARY=$takeover_nodes

        profile=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep PROFILE_NAME)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
             exit 1
        }
        PROFILE_NAME=$(echo $profile | cut -d"=" -f2)

        path=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep INSTALL_PATH)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
             exit 1
        }
        INSTALL_PATH=$(echo $path | cut -d"=" -f2)

        KLIB_AIX_add_vg_by_path INSTALL_VG $INSTALL_PATH "$INSTALL_VG"

        VG_PVIDS=$(KLIB_AIX_get_pvids_by_vgs "$INSTALL_VG")

        ipaddr=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep IPAddress_or_name)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
             exit 1
        }
        ENDPOINT_HOST=$(echo $ipaddr | cut -d"=" -f2)
        SERVICE_IP_LABEL=${ENDPOINT_HOST}

        netmask=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE | grep Prefix_or_Netmask)
        (( $? != 0 )) && {
            dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
             exit 1
        }
        SERVICE_IP_LABEL_PREFIX=$(echo $netmask | cut -d"=" -f2)


        # Remove old discovery file
        rm -f $WASSA_DISC_FILE

        DATE=$(date +"%m/%d/%y %H:%M:%S")

        echo "#" >> $WASSA_DISC_FILE
        echo "# This ksh93 source file was generated on $DATE" >> $WASSA_DISC_FILE
        echo "# Do NOT alter the content of this file" >> $WASSA_DISC_FILE
        echo "#" >> $WASSA_DISC_FILE
	

	echo "unset $APPLICATION_NAME" >> $WASSA_DISC_FILE
        echo "typeset -A $APPLICATION_NAME" >> $WASSA_DISC_FILE
        echo "$APPLICATION_NAME=( \\" >> $WASSA_DISC_FILE
        echo "\t[WAS_CELL_NAME]=\"${WAS_CELL_NAME}\"" >> $WASSA_DISC_FILE
        echo "\t[WAS_NODE_NAME]=\"${WAS_NODE_NAME}\"" >> $WASSA_DISC_FILE
        echo "\t[WAS_SERVER_NAME]=\"${WAS_SERVER_NAME}\"" >> $WASSA_DISC_FILE
        echo "\t[WAS_TYPE]=\"APPLICATION_SERVER\"" >> $WASSA_DISC_FILE

        if [[ $disc_type == "TRANSACTIONLOG" ]]; then
            echo "\t[DM_NODE_NAME]=\"${PRIMARY}\"" >> $WASSA_DISC_FILE
        else
            echo "\t[INSTALL_NODE_NAME]=\"${PRIMARY}\"" >> $WASSA_DISC_FILE
        fi

        echo "\t[PROFILE_NAME]=\"${PROFILE_NAME}\"" >> $WASSA_DISC_FILE

        if [[ $disc_type == "TRANSACTIONLOG" ]]; then
            echo "\t[PROFILE_PATH]=\"${profile_path}\"" >> $WASSA_DISC_FILE
            echo "\t[INSTALL_PATH]=\"${INSTALL_PATH}\"" >> $WASSA_DISC_FILE
            echo "\t[VERSION]=\"${VERSION}\"" >> $WASSA_DISC_FILE
            echo "\t[WAS_MEMBER_KEYS]=\"\"" >> $WASSA_DISC_FILE

        else
            echo "\t[INSTALL_PATH]=\"${INSTALL_PATH}\"" >> $WASSA_DISC_FILE
            echo "\t[INSTALL_VGS]=\" ${INSTALL_VG}\"" >> $WASSA_DISC_FILE
            echo "\t[VG_PVIDS]=\"${VG_PVIDS}\"" >> $WASSA_DISC_FILE
            echo "\t[ENDPOINT_HOST]=\"${SERVICE_IP_LABEL}\"" >> $WASSA_DISC_FILE
            echo "\t[VERSION]=\"${VERSION}\"" >> $WASSA_DISC_FILE
        fi
        echo ")" >> $WASSA_DISC_FILE
        echo ""  >> $WASSA_DISC_FILE
}
################################################################################
#
# Name:         importConfigFromFile
#
# Description:
#               This function will read the supplid config file and create HACMP
#               resources to configure WAS for HA.
#
# Arguments:
#               None
#
# Returns:
#               0 - on success
#               1 - on failure
#
################################################################################

importConfigFromFile() {
    [[ "$VERBOSE_LOGGING" == "high" ]] && set -x

    [[ "$COMPONENT_ID" == "FILENET_CONTENT_ENGINE" ]] && {
	MANUAL_CONFIG_TYPE="Content_Engine_Application_Server"
    }

    [[ "$COMPONENT_ID" == "FILENET_APPLICATION_ENGINE" ]] && {
	MANUAL_CONFIG_TYPE="Application_Engine_Application_Server"
    }

    configure_was_node=$(clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA -t $MANUAL_CONFIG_TYPE -a configure)
    (( $? != 0 )) && {
         dspmsg -s $MANUAL_CONFIG_SET $WASSACAT 1 "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
         exit 1
    }
    if [[ -n $configure_was_node && $configure_was_node == "yes" ]]; then

	[[ "$COMPONENT_ID" == "FILENET_CONTENT_ENGINE" ]] && {
        ce_install_path=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA \
-t $MANUAL_CONFIG_TYPE | grep CE_INSTALL_PATH)

        [[ -n $ce_install_path ]] && {
                ce_install_path=$(echo $ce_install_path | cut -d"=" -f2)
                export CE_INSTALL_PATH="$ce_install_path"
        }
    }

    [[ "$COMPONENT_ID" == "FILENET_APPLICATION_ENGINE" ]] && {
        ae_install_path=$(LC_ALL=C clsaxmlutil -s -x $CONFIG_FILE -m $FILENET_CE_AE_MANUAL_CONFIG_SCHEMA \
-t $MANUAL_CONFIG_TYPE | grep AE_INSTALL_PATH)

        [[ -n $ae_install_path ]] && {
                ae_install_path=$(echo $ae_install_path | cut -d"=" -f2)
                export AE_INSTALL_PATH="$ae_install_path"
        }
    }

        createDiscoveryFile "$MANUAL_CONFIG_TYPE"

        if [[ -z $SERVICE_IP_LABEL_PREFIX ]]; then
            $WASSA_SBIN_DIR/cl_wasimport -a -t "APPSERVER" -A "$APPLICATION_NAME" -c \
"$WAS_CELL_NAME" -N "$WAS_NODE_NAME" -o "$PRIMARY" -n "$SECONDARY" -s "$SERVICE_IP_LABEL"
        else
            $WASSA_SBIN_DIR/cl_wasimport -a -t "APPSERVER" -A "$APPLICATION_NAME" -c \
"$WAS_CELL_NAME" -N "$WAS_NODE_NAME" -o "$PRIMARY" -n "$SECONDARY" -s "$SERVICE_IP_LABEL" \
-P "$SERVICE_LABEL_PREFIX"
        fi

    fi
}

##########
# MAIN
##########

# Read in the message catalog entries

# Load the common functions, logmsg, dbgmsg, errmsg, abort
. /usr/es/lib/ksh93/common_functions.ksh93

umask -S u=rw,g=,o=

PROGNAME=$(basename ${0})
PATH="$($(dirname ${0})/../../../utilities/cl_get_path all)"
PATH=$PATH:/usr/bin:/etc:/usr/sbin:/usr/ucb:/sbin:/usr/es/sbin/cluster/sa/sbin
FPATH_BASE=/usr/es/lib/ksh93
FPATH=$FPATH_BASE/hacmp:$FPATH_BASE/sa:$FPATH_BASE/aix:$FPATH_BASE/aix/odm:$FPATH_BASE/util/list
export PATH FPATH

[[ "$VERBOSE_LOGGING" == "high" ]] && set -x

WASSACAT="wassa.cat"
CONF_MSGSET=7
IMPORT_MSGSET=8

WASSA_HOME="/usr/es/sbin/cluster/sa/was"
WASSA_ETC_PATH="$WASSA_HOME/etc"
WASSA_SBIN_DIR="$WASSA_HOME/sbin"
WASSA_DISC_FILE="$WASSA_ETC_PATH/was.disc"
FILENET_CE_AE_MANUAL_CONFIG_SCHEMA="/usr/es/sbin/cluster/sa/filenet/config/cl_filenet_manual_config.xsd"

APPLICATION_NAME=""

# Get the arguments.
if set -- $(getopt A:n:h:s:o:N:c:t:m:P:f:C:aru $* 2>&1); then
    while [ $# != 0 ]; do
        case "$1" in

            -A)
            
            APPLICATION_NAME=$2
            shift
            ;;

            -h)
            
            HTTPSERVER=$2
            shift
            ;;

            -s)
            
            SERVICE_IP_LABEL=$2
            shift
            ;;

            -n)
            SECONDARY="$SECONDARY $2"
            shift
            ;;

            -o)
            
            PRIMARY=$2
            shift
            ;;

            -N)
            
            WEBSPHERE_NODE=$2
            shift
            ;;


            -c)
            
            CELL=$2
            shift
            ;;


            -t)
            
            COMPONENT_TYPE=$2
            shift
            ;;


            -m)
            
            DM_SERVER_NAME=$2
            shift
            ;;


            -a)
            
            ACTION="add"
            ;;

            -r)
            ACTION="remove"
            ;;

            -u)
            ACTION="update"
            ;;

            -C)

            COMPONENT_ID=$2
            shift
            ;;

	    -P)

	    NETMASK_PREFIX_LEN=$2
	    shift
	    ;;

	    -f)

	    MANUAL_CONFIG=true
	    CONFIG_FILE=$2
	    shift
	    ;;

            --)
            shift
            break
            ;;
        esac
        shift
    done
fi


#
# Before handling anything else, check if we have to configure from XML
#
if [[ $MANUAL_CONFIG == true ]]; then
    if [[ ! -f $CONFIG_FILE ]]; then
        dspmsg -s 51 cluster.cat 26 "Unable to read the configuration file. Please ensure the correct path"
        return 1
    fi
    importConfigFromFile
    exit 0
fi


if [[ -z $COMPONENT_TYPE || -z $ACTION ]] ; then
    usage
    exit 1
fi


if [[ "$ACTION" == "add" || "$ACTION" == "update" ]]; then

    if [[ "$COMPONENT_TYPE" == "APPSERVER" ]]; then 
        if [[ -z ${CELL} || -z ${WEBSPHERE_NODE} ]] ; then
            usage
            exit 1
        fi

        INSTANCE_KEY="WAS_NODE_${CELL}_${WEBSPHERE_NODE}"
    fi

    if [[ "$COMPONENT_TYPE" == "HTTPSERVER" ]]; then 
        if [[ -z ${HTTPSERVER} ]] ; then
            usage
            exit 1
        fi

        COMPONENT_ID="WAS_6.0_IHS_SERVER"
        INSTANCE_KEY="WAS_IHS_${HTTPSERVER}"
    fi

    if [[ "$COMPONENT_TYPE" == "DMMANAGER" ]]; then 
        if [[ -z ${CELL} ]] ; then
            usage
            exit 1
        fi

        COMPONENT_ID="WAS_6.0_DEPLOYMENT_MANAGER"
        INSTANCE_KEY="WAS_DM_${CELL}"
    fi

    # Do pre smart assist stuff
	clsapre

    if [[ -z ${PRIMARY} || -z ${SECONDARY} || -z ${SERVICE_IP_LABEL} ]] ; then
        usage
        exit 1
    fi

    if [[ "$ACTION" == "add" ]] ; then

        if [[ -z $APPLICATION_NAME ]] ; then
            APPLICATION_NAME="$INSTANCE_KEY"
        fi

        # Add all the required odm objects.
        AddResources
        if (( $? != 0 )); then
            
            # Something went wrong so clean-up as best as possible
            RemoveHACMPResources
            clrmsaapp -a ${APPLICATION_NAME}
            
            exit 1
        fi
    fi
    
    if [[ "$ACTION" == "update" ]] ; then
        UpdateResources
        
        if (( $? != 0 )); then
            exit 1
        fi
    fi
    
    # Do post smart assist stuff. Verification won't be done.
	clsapost
fi


if [[ "$ACTION" == "remove" ]]; then
    if [[ -z ${APPLICATION_NAME} ]] ; then
        usage
        exit 1
    fi
    
    # At this point, the resource group has been removed.

    ResetWASConfig
    if (( $? != 0 )); then
        exit 1
    fi
fi

exit 0
