#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2017,2018,2019,2020,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#
#  @(#)  7d4c34b 43haes/usr/sbin/cluster/sa/sap/sbin/cl_addsapinstance.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM                                                                              
##
## NAME:
##  cl_addsapinstance
##
## PURPOSE:
##  Creates HACMP configurations for different SAP instance types such as 
##  Application Server instances, SCS instances, ERS instances and 
##  also SAP Global filesystem
##
## ARGUMENTS:
##
##  Adding SAP Global File System
##      :== -t GFS
##          -p <pri node> 
##          -T <takeover nodes>
##          -I <Service IP/Virtual IP>        
##          -V <Shared VGs> 
##          -E <Export Directories>
##          -M <NFS mounts>
##
##  Adding Application Server Instance
##      :== -t AS
##          -s SAP System ID
##          -i <instance name>
##          -a <application name>
##          -p <pri node> 
##          -T <takeover nodes>
##          -I <Service IP/Virtual IP>        
##          -n <Service Network> 
##          -V <Shared VGs> 
##          -r <DBRG> 
##  Adding SCS Instance
##      :== -t SCS
##          -s SAP System ID
##          -i <instance name>
##          -a <application name>
##          -p <pri node> 
##          -T <takeover nodes>
##          -I <Service IP/Virtual IP>        
##          -n <Service Network>
##          -V <Shared VGs> 
##          -r <DBRG> 
##  Adding ERS Instance
##      :== -t ERS
##          -s SAP System ID
##          -i <instance name>
##          -a <application name>
##          -P <participating nodes>
##          -I <Service IP/Virtual IP>        
##          -n <Service Network> 
##          -V <Shared VGs> 
##  Manual Configuration
##          -f <absolute path to template xml>
##
## RETURNS
##  0 on success
##  1 on failure
##

. /usr/es/lib/ksh93/func_include
version='1.61'

#----------------------------------------------------------------------------
# Global Definitions
#----------------------------------------------------------------------------

. /usr/es/sbin/cluster/sa/sap/etc/SAPGlobals
. /usr/es/sbin/cluster/sa/sap/sbin/SAPUtilities


PATH=$PATH:/usr/es/sbin/cluster/sa/sbin
PATH=$(/usr/es/sbin/cluster/utilities/cl_get_path all)
typeset PROGRAM=${0##*/}

typeset PRINODE TAKENODE # primary and takeover nodes
typeset PARTICIPATING_NODES
typeset -A participating_nodes
typeset SHAREDVGS        # shared volume groups
typeset SERVICE_LABEL    # service IP label
typeset APPLICATION_ID   # Application ID for App Discovery
typeset SAP_GLOBALS="SAP_GLOBALS"
typeset SAPSYSTEMNAME

typeset SMARTASSIST_ID="SAPNW"
typeset COMPONENT_ID=
typeset INSTANCE         # SAP Instance Name
typeset MOUNT_DIR        
typeset EXPORT_DIR
typeset SAPSID           # SAP SYSTEM ID (SID)
typeset INSTANCE_NO      # SAP Instance number
typeset MANUAL_CONFIG=false #Manual Configuration mode
typeset CONFIG_FILE=""
typeset SERVICE_LABEL_PREFIX    # service IP label prefix
typeset SERVICE_NETWORK  # Network for service IP
typeset DBRG               # Database RG
typeset PROFILE
typeset EXECUTABLE
typeset SETTLE_TIME
typeset ERS_MISC_DATA
typeset EXISTING_ERS_MISC_DATA=""
typeset RG_OF_THE_VG=""
typeset APP_NAME=""
typeset RG_OF_THE_SERVICE_IP=""
typeset ERS_DATA=""
typeset PRI_ERS=""
typeset PRI_ERS_NO=""
typeset EXISTING_MISC_DATA=""
typeset EXISTING_SERVICE_LABELS=""
typeset EXISTING_APPLICATIONS=""
typeset EXISTING_VGS=""
typeset SAP_INSTANCE_EXE=""
typeset NFS_COUNT=""
typeset IS_NFS=0
typeset NFS_IP=""
typeset SAPMNT_NFS=""
typeset IS_RESOURCE_REUSED="FALSE"
typeset IS_VG_REUSED="FALSE"
typeset IS_IP_REUSED="FALSE"
typeset IS_ERS_GROUPED="FALSE"
typeset IS_ERS_RG_MODIFIED="FALSE"
typeset SAP_MANUAL_CONFIG_SCHEMA="/usr/es/sbin/cluster/sa/sap/config/cl_sap_manual_config.xsd"
typeset rc=0
typeset current_serviceip 
typeset current_vg
typeset -i pcount=0

#----------------------------------------------------------------------------

#----------------------------------------------------------------------------
# Function:
#   addConnectorMetaData 
#
# Purpose:
#   To add metadata entries to HACMPsap_connector ODM
#
# Arguments:
#   application_id 
#     <name=value> 
#
# Returns:
#   0 For sucess
#   1 For failure
#
#----------------------------------------------------------------------------

function addConnectorMetaData
{

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

    typeset VARGS
    typeset CONN_ODM=HACMPsap_connector
    typeset finalEntries=""
    typeset -A list

    if set -- $(getopt a: $* 2>&1); then
	while (( $# != 0 )); do
	case "$1" in
	-a)
	    APP_ID=$2
	    shift
	    ;;
	--)
	    shift
	    VARGS=$*
	    break
	    ;;
	esac
	shift
	done
    fi

    for nameValuePair in $VARGS
    do
        NAME=${nameValuePair/=*/}
        VALUE=${nameValuePair/*=/}
        [[ -n $finalEntries ]] && {
            finalEntries="$finalEntries $nameValuePair"
        }
        [[ -z $finalEntries ]] && {
            finalEntries="$nameValuePair"
        }
    done

     KLIB_UTIL_parse_arguments list $finalEntries >/dev/null

    for name in ${!list[*]}; do
        # delete Previous entries to avoid duplicates
        deleteConnectorMetaData APP_ID name
        echo "$CONN_ODM:"
        echo "  application_id=$APP_ID"
        echo "  name=$name"
        echo    value="${list[$name]}"
        echo
    done | odmadd

}

#----------------------------------------------------------------------------
# Function:
#   deleteConnectorMetaData
#
# Purpose:
#   To add metadata entries to HACMPsap_connector ODM
#
# Arguments:
#   application_id
#     <name=value>
#
# Returns:
#   0 For sucess
#   1 For failure
#
#----------------------------------------------------------------------------

function deleteConnectorMetaData
{
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset -n appid=$1
    typeset -n entries=$2
    typeset CONN_ODM=HACMPsap_connector

    shift
    FPATH=$FPATH:/usr/es/lib/ksh93/util/
    [[ -z $entries ]] && {
        /usr/bin/odmdelete -o $CONN_ODM -q "application_id=$appid" \
            >/dev/null 2>&1
        return $?
    }

    [[ -n $entries ]] && {
        typeset -A dellist
        typeset query
        typeset name
        typeset value
        typeset en

        if ! echo $entries | grep "="
        then
	    for en in $entries; do
		query="application_id=$appid and name=$en"
		/usr/bin/odmdelete -o $CONN_ODM -q "$query" >/dev/null 2>&1 ||
			return 1
	    done
        else
	    KLIB_UTIL_parse_arguments dellist $entries

	    for name in ${!dellist[*]}
	    do
		query="application_id=$appid and name=$name and value=${dellist[$name]}"
		/usr/bin/odmdelete -o $CONN_ODM -q "$query" >/dev/null 2>&1 ||
			return 1
	    done
        fi
     }
}

#----------------------------------------------------------------------------
# Function:
#   addSAPGFS
#
# Purpose:
#   To Create HACMP resources and resource group for managing SAP Global
#   filesystems.
#
# Arguments:
#   None.
#
# Returns:
#   0 For sucess
#   1 For failure
#
#----------------------------------------------------------------------------

function addSAPGFS {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    setSAPGlobalEnv $SAPSID
    typeset -L64 rgname=$(echo "SAP_"$SAPSID"_NFS_RG")
    typeset APPLICATION_ID=$(echo "SAP_"$SAPSID"_GFS")
    typeset -i ret
    typeset nodes
    typeset SAPADMNUSR
    typeset lib_output
    typeset directory_output
    typeset directory_present
    
    KLIB_SAP_SA_logmsg INFO 120 23 sapsa.cat "INFO: Please follow below steps for avoiding NFS outage using below steps \n"
    SAPADMNUSR=$(echo $SAPSID | tr '[:upper:]' '[:lower:]')adm
    lib_output=$(/usr/bin/su - $SAPADMNUSR -c 'env LANG=C echo $LIBPATH')
    while read line;do
	directory_output=$(echo $line | grep $SID | awk ' {print $1}' | awk -F "=" ' {print $2}' | awk -F ":" ' {print $1}')
	directory_present=$(echo "$lib_output" | grep -w "$directory_output" )
	if [[ -z $directory_present ]];then
	    KLIB_SAP_SA_logmsg INFO 120 24 sapsa.cat "The directory %s is not present in LIBPATH. Please execute below command.\n" $directory_output
	    KLIB_SAP_SA_logmsg INFO 120 25 sapsa.cat "1. /usr/bin/su - %s \n" $SAPADMNUSR
	    KLIB_SAP_SA_logmsg INFO 120 29 sapsa.cat "2. echo \"env LIBPATH=\${LIBPATH}:"%s" \" >> .cshrc \n " $directory_output
	fi
    done < /usr/sap/sapservices
    
    COMPONENT_ID="SAPNW_SAPGFS"    
    
    rgname=$(getUnusedName $rgname "resource_group")
    
    isVGsAlreadyDefined VOLUME_GROUPS
    isServiceIPLabelAlreadyDefined $SERVICE_LABEL
    
    #Adding SAP_RG_NFS Resource Group to support SAP Global Filesystem
    KLIB_SAP_SA_logmsg INFO 40 1 sapsa.cat "Adding %s Resource Group to support SAP Global Filesystem.\n" $rgname
    
    #Adding Service IP Label
    addServiceIPLabel
    
    clmgr add resource_group $rgname \
        PRIMARYNODES="$PRINODE $TAKENODE" \
        STARTUP="OFAN" \
        FALLBACK="NFB" \
        FALLOVER="FNPN" || {
            KLIB_SAP_SA_logmsg ERROR 30 2 sapsa.cat "Unexpected error encountered while attempting to create resource group: %s\n" $rgname
            InternalErrorAbort
        }
    
    clmgr modify resource_group $rgname \
        VOLUME_GROUP="$VOLUME_GROUPS" \
        VG_AUTO_IMPORT="false" \
        FORCED_VARYON="false" || {
	    KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
	    clmgr -f delete resource_group $rgname
	    InternalErrorAbort
	}
    #check to see if stable storage path already exist for sap GFS
    [[ ! -d "/.SS/$VOLUME_GROUPS" ]] && {
       #Creating a stable storage path file system and redirecting any error to KSSLOGFILE. KSSLOGFILE is initialized to /var/hacmp/log/sapsa.log file in SAPGlobals.
       cl_crlvfs -cspoc "-g $rgname" -v "jfs2" -g "$VOLUME_GROUPS" -m "/.SS/$VOLUME_GROUPS" -p "rw" -a "size=1048576" 2>>$KSSLOGFILE
       (( $? != 0 )) && {
         KLIB_SAP_SA_logmsg ERROR 30 49 sapsa.cat "ERROR: Unable to create file system for stable storage path.\n"
         InternalErrorAbort
       }
    }   
    #Adding mandatory stable storage path for SAP GFS
    clmgr modify resource_group $rgname \
	SERVICE_LABEL="$SERVICE_LABEL" \
	VOLUME_GROUP="$VOLUME_GROUPS" \
	VG_AUTO_IMPORT="false" \
	FORCED_VARYON="false" \
	FSCHECK_TOOL="fsck" \
	FS_BEFORE_IPADDR="true" \
	FILESYSTEM="" \
	EXPORT_FILESYSTEM_V4="$EXPORT_DIR" \
        STABLE_STORAGE_PATH="/.SS/$VOLUME_GROUPS" \
	MOUNT_FILESYSTEM="$MOUNT_DIR" || {
	    KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
	    clmgr -f delete resource_group $rgname
	    InternalErrorAbort
	}
  
    # Associate the application with the resource group
    claddsaapp -a $APPLICATION_ID \
        RESOURCE_GROUP="$rgname" \
        SAPSYSTEMNAME="$SAPSYSTEMNAME" \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        APPLICATION_NAME="$APPLICATION_ID"

    (( $? != 0 )) && { # Internal Error
	KLIB_SAP_SA_logmsg ERROR 120 13 sapsa.cat "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror. \n" $APPLICATION_ID
        InternalErrorAbort
    }
    nodes=$(clmgr query node)
    generateVerifyScript $APPLICATION_ID "SAPNW_SAPGFS" nodes

    cltopinfo
    KLIB_SAP_SA_logmsg INFO 120 17 sapsa.cat "INFO: Successfully configured Application %s.\n" $APPLICATION_ID
    return $?
}

#----------------------------------------------------------------------------
# Function:
#   addSAPSCSInstance
#
# Purpose:
#   To Create HACMP resources and resource group for managing SAP Central 
#   Services Instance(s). There may be two SCS instances running in a given SAP
#   system, however, HACMP manages both of them in a single resource group.
#
# Arguments:
#   None.
#
# Returns:
#   0 For sucess
#   1 For failure
#----------------------------------------------------------------------------

function addSAPSCSInstance {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset instances instance_nos out rglist rg
    typeset -L64 APP_ID=$APPLICATION_ID 
    typeset -L64 rgname=$(echo "SAP_"$SAPSID"_"$INSTANCE"_RG")
    typeset -L64 appname=$(echo $SAPSID"_"$INSTANCE"_AP")
    typeset -L64 appmonname=$(echo $SAPSID"_"$INSTANCE"_AM")
    typeset -L64 GSA_APP=$(echo "SAP_"$SAPSID"_GFS")
    typeset service_ips
    typeset -i count count1
    typeset gfs_nodes
    typeset -i STAB_INT=240
    typeset instance_profile instance_num local_node_name inst_profile instance_start_profile
    local_node_name=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
    COMPONENT_ID="SAPNW_SCSINSTANCE"
    IS_RESOURCE_REUSED="FALSE"
    IS_IP_REUSED="FALSE"
    IS_VG_REUSED="FALSE"
    IS_DEPENDENCY_DEFINED="FALSE"
    SAP_GLOBALS="SAP_GLOBALS"

   #Adding Discovered SAP SCS instances to HACMP configuration
    KLIB_SAP_SA_logmsg INFO 40 4 sapsa.cat "Adding Discovered SAP SCS instances: %s to HACMP configuration.\n" $INSTANCE
 
    rgname=$(getUnusedName $rgname "resource_group")
    appname=$(getUnusedName $appname "application")
    appmonname=$(getUnusedName $appmonname "application_monitor")

   # check if instance has already been added 
    /usr/es/sbin/cluster/utilities/clodmget -n -q "name=INSTANCE_NUMBERS" -f value HACMPsa_metadata | while read line
    do
       #check if the instance is already configured to PHA
       if [[ $line == $INSTANCE_NO ]]
       then
           KLIB_SAP_SA_logmsg ERROR 120 1 sapsa.cat "ERROR: SAP Instance \"%1\$s\" is already configured to be highly available through PowerHA SM. Exiting." $INSTANCE 
           exit 1;
       fi	 
   done

    setSAPGlobalEnv $SAPSID
    ret=$?
    (( $ret != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 12 sapsa.cat "Unexpected error encountered while setting up SAP Global Environment.\n"
        InternalErrorAbort
    }

    #check if the profiles exists and the instance numbers are correct.

      # Set START_PROFILE
                instance_start_profile=$SAPPROFILEDIR"/START_"$INSTANCE"_"$SERVICE_LABEL

      # Set INSTANCE_PROFILE
                inst_profile=$SAPPROFILEDIR"/"$SAPSID"_"$INSTANCE"_"$SERVICE_LABEL

       if [ -f ${instance_start_profile} ]; then
          instance_profile=${instance_start_profile};
       else
          instance_profile=${inst_profile};
      fi

        [[ ! -f $instance_profile ]] && {
            KLIB_SAP_SA_logmsg ERROR 30 23 sapsa.cat "Unable to find Startup profile %s for instance %s\n" $instance_profile $INSTANCE
            InternalErrorAbort
        }
        instance_num=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C $SAPEXEDIR/sappfpar \
                      pf=$instance_profile SAPSYSTEM" 2>/dev/null)
        (( $instance_num != $INSTANCE_NO )) && {
            KLIB_SAP_SA_logmsg ERROR 30 24 sapsa.cat "Discovered instance number for instance %s is not matching.Possible wrong instance startup profile %s.\n" $INSTANCE $instance_profile
            InternalErrorAbort
        }

    PROFILE=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
         sapcontrol -nr $instance_num \
         -function ParameterValue SAPPROFILE -format script " 2>/dev/null \
      | grep "^0 :" | cut -f2 -d :)

    [[ -z $PROFILE ]] && {
         KLIB_SAP_SA_logmsg INFO 60 7 sapsa.cat "ERROR: %s : No output from sapcontrol for process status\n" $PROGRAM
        exit 1
    }

    SAP_INSTANCE_EXE=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
         sapcontrol -nr $instance_num \
         -function ParameterValue DIR_EXECUTABLE -format script " 2>/dev/null \
      | grep "^0 :" | cut -f2 -d :)

    [[ -z $SAP_INSTANCE_EXE ]] && {
        KLIB_SAP_SA_logmsg INFO 60 7 sapsa.cat "ERROR: %s : No output from sapcontrol for process status\n" $PROGRAM
        exit 1
    }


    KLIB_SAP_SA_logmsg INFO 120 8 sapsa.cat "INFO: SAP Instance \"%1\$s\" EXE directory is \"%2\$s\" ." $INSTANCE $SAP_INSTANCE_EXE
    KLIB_SAP_SA_logmsg INFO 120 9 sapsa.cat "INFO: SAP Instance \"%1\$s\" Profile is \"%2\$s\"." $INSTANCE $PROFILE

 if [[ $VOLUME_GROUPS != "LOCAL" ]] ; then
    isVGsAlreadyDefined VOLUME_GROUPS
    if (( $? == 1 ))
    then
        # This means the VG is already defined to SM. so set following variable to TRUE
        IS_RESOURCE_REUSED=TRUE
        IS_VG_REUSED=TRUE

        #The code should proceed by grouping the current instance to the RG to which resource has already been defined.
        RG_OF_THE_VG=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=VOLUME_GROUP and value=$VOLUME_GROUPS" -f group HACMPresource)
        rgname=$RG_OF_THE_VG
        KLIB_SAP_SA_logmsg INFO 120 2 sapsa.cat "INFO: Since the VG \"%1\$s\" seems to be already defined as a resource to PowerHA SM, the instance \"%2\$s\" will be grouped with the Resource Group \"%3\$s\"." $VOLUME_GROUPS $INSTANCE $rgname

	# get the app_ID of this RG from HACMPsa_metadata , if there is no app_ID in metadata, then add entries in HACMPsa_metadata with new APP_NAME}
        APP_NAME=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=RESOURCE_GROUP and value=$rgname" -f application_id HACMPsa_metadata)
        if [[ -n $APP_NAME ]]
        then
            APP_ID=$APP_NAME; 
            KLIB_SAP_SA_logmsg INFO 120 3 sapsa.cat "INFO: Please note that the instance \"%1\$s\" will be grouped with RG \"%2\$s\" of Application \"%3\$s\"." $INSTANCE $rgname $APP_ID
        fi
    fi
fi

if [[ $SERVICE_NETWORK != "LOCAL" ]] ; then
        isServiceIPLabelAlreadyDefined $SERVICE_LABEL
    	if (( $? == 1 ))
    	then
           # This means the service_ip is already defined to PHA . so set following variable to TRUE
           IS_RESOURCE_REUSED=TRUE
	   IS_IP_REUSED=TRUE

           #The code should proceed by grouping the current instance to the RG to which resource has already been defined.
	   RG_OF_THE_SERVICE_IP=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=SERVICE_LABEL and value=$SERVICE_LABEL" -f group HACMPresource)

           # Now this will become the rgname for new instance as well.
           rgname=$RG_OF_THE_SERVICE_IP
            KLIB_SAP_SA_logmsg INFO 120 4 sapsa.cat "INFO: Since the Service IP label seems to be already defined as a resource to PowerHA SM, The instance \"%1\$s\"  will be grouped with the Resource Group \"%2\$s\"." $INSTANCE $rgname

           # get the app_ID of this RG from HACMPsa_metadata , if there is no app_ID in metadata, then add entries in HACMPsa_metadata with new APP_NAME}
           APP_NAME=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=RESOURCE_GROUP and value=$rgname" -f application_id HACMPsa_metadata)
           if [[ -n $APP_NAME ]]
           then
                APP_ID=$APP_NAME;
                KLIB_SAP_SA_logmsg INFO 120 3 sapsa.cat "INFO: Please note that the instance \"%1\$s\" will be grouped with RG \"%2\$s\" of Application %3$s." $INSTANCE $rgname $APP_ID
           fi
        fi

    fi 

  # Get the SAP GFS APP_ID
  SAPGFSAPPID=$( /usr/es/sbin/cluster/utilities/clodmget -n -q "name=APPLICATION_NAME and application_id=$GSA_APP" -f value HACMPsa_metadata)

    #check if we have SAP global file system configured.
    [[ -z $SAPGFSAPPID ]] && {
        KLIB_SAP_SA_logmsg WARN 30 39 sapsa.cat "WARNING: Did not discover Smart Assist enabled NFSv4 SAP Global File System.\n\
                           Continuing on the assumption that administrator has used alternate \
                           methods (GPFS, NFS in another cluster etc) to setup highly available \
                           SAP Global File System. \n"
    } || {   
    
        #check, if the primary and take over nodes are SAP GFS ready?
        gfs_nodes=$(getNodes $SAPGFSAPPID)
        for node in "$PRINODE $TAKENODE"; do
            KLIB_UTIL_LIST_is_in_list gfs_nodes $node || {
            KLIB_SAP_SA_logmsg ERROR 30 26 sapsa.cat "SAP Global File system is not configured on %s node where %s has been selected to run.\n"$node $INSTANCE 
            InternalErrorAbort
            }
        done
    }
    
    #If the IP is not node bound then Check it is an aliased IP or not?
    if [[ $SERVICE_NETWORK != "LOCAL" ]] ; then 

        [[ "$local_node_name" == "$PRINODE" ]] && {
            cl_checkIsAliasAddr $SERVICE_LABEL
        } || {
            cl_rsh $PRINODE "/usr/es/sbin/cluster/sa/sap/sbin/cl_checkIsAliasAddr $SERVICE_LABEL"
        }
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 30 27 sapsa.cat "SAP Instance name: %s is configured to run on node %s with an IP %s which is found to be an a non aliased address.\n" $INSTANCE $PRINODE $SERVICE_LABEL
            InternalErrorAbort
        }
    fi

  if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]]
  then 
    #Creating Resource Group for managing SCS instances
    KLIB_SAP_SA_logmsg INFO 40 5 sapsa.cat "Adding %s Resource Group to support SAP SCS instances: %s\n" $rgname $INSTANCE
    
     clmgr add resource_group $rgname \
        PRIMARYNODES="$PRINODE $TAKENODE" \
        STARTUP="OFAN" \
        FALLBACK="NFB" \
        FALLOVER="FNPN" || {
            KLIB_SAP_SA_logmsg ERROR 30 2 sapsa.cat "Unexpected error encountered while attempting to create resource group: %s\n " $rgname
            InternalErrorAbort
        }    
  fi

if [[ "$SERVICE_NETWORK" != "LOCAL" ]]; then

    if [[ "$IS_IP_REUSED" == "FALSE" ]]; then
        addServiceIPLabel
    fi
fi

  if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]]
  then

    # Creating application controller ...
    KLIB_SAP_SA_logmsg INFO 40 19 sapsa.cat "\tCreating PowerHA SystemMirror application controller: %s\n" $appname

    startscript="$SAPSA_SBIN/cl_sapStart -a $APP_ID"
    stopscript="$SAPSA_SBIN/cl_sapStop -a $APP_ID"


    clmgr add application $appname \
    STARTSCRIPT="$startscript" \
    STOPSCRIPT="$stopscript" \
    STARTUP_MODE="foreground"
    
    (( $? != 0 )) && {
         KLIB_SAP_SA_logmsg ERROR 30 46 sapsa.cat "Unexpected error encountered while attempting to create PowerHA SystemMirror application controller: %s\n" $appname
        InternalErrorAbort
    }

    # Creating custom application monitor
    KLIB_SAP_SA_logmsg INFO 40 8 sapsa.cat "\tCreating PowerHA SystemMirror application monitor: %s\n" $appmonname

    claddappmon name=$appmonname \
        MONITOR_TYPE='user' \
        RESOURCE_TO_MONITOR=$appname \
        INVOCATION='longrunning' \
        FAILURE_ACTION='fallover' \
        RESTART_METHOD="$startscript" \
        CLEANUP_METHOD="$stopscript" \
        MONITOR_METHOD="$SAPSA_SBIN/cl_sapMonitor -a $APP_ID" \
        MONITOR_INTERVAL='60' \
        HUNG_MONITOR_SIGNAL='9' \
        STABILIZATION_INTERVAL="$STAB_INT" \
        RESTART_COUNT='0' \
        RESTART_INTERVAL='792' >/dev/null 2>&1

    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 5 sapsa.cat "Unexpected error encountered while attempting to create PowerHA SystemMirror application monitor: %s\n" $appmonname
        InternalErrorAbort
    }
  fi

## Handle case - Resources sharing 
if [[ "$IS_RESOURCE_REUSED" == "TRUE" ]]
then

     if [[  "$IS_VG_REUSED" == "TRUE" ]]
     then
        current_serviceip=$SERVICE_LABEL
        EXISTING_SERVICE_LABELS=$(/usr/es/sbin/cluster/utilities/clmgr -a SERVICE_LABEL query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
        SERVICE_LABEL="$EXISTING_SERVICE_LABELS $SERVICE_LABEL"
	if [[ "$SERVICE_NETWORK" != "LOCAL" || "$IS_IP_REUSED" != "TRUE" ]]; then
		KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
		clmgr modify resource_group $rgname \
			SERVICE_LABEL="$SERVICE_LABEL" \
			VG_AUTO_IMPORT="false"
		rc=$?
	

           (( $rc != 0 )) && { # Internal Error
              KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
              # delete service IP from existing RG.
              clmgr -f delete application_monitor $appmonname
              clmgr -f delete application $appname
              InternalErrorAbort
            }
         fi
     else
       if [[ "$IS_IP_REUSED" == "TRUE"  ]]
       then
           current_vg=$VOLUME_GROUPS
           EXISTING_VGS=$(/usr/es/sbin/cluster/utilities/clmgr -a VOLUME_GROUP query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
           VOLUME_GROUPS="$EXISTING_VGS $VOLUME_GROUPS"
	       if [ $current_vg != "LOCAL" ]; then
		      KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
		      clmgr modify resource_group $rgname \
			    VOLUME_GROUP="$VOLUME_GROUPS" \
			    VG_AUTO_IMPORT="false"
		      rc=$?    
	

             (( $rc != 0 )) && { # Internal Error
               KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
               # delete vg name from existing RG.
               clmgr -f delete application_monitor $appmonname
               clmgr -f delete application $appname
               InternalErrorAbort
             }
           fi
       fi
     fi
else 

    ## Handle case - Local File system / Network Configurations
    KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE

    if [ $VOLUME_GROUPS == "LOCAL" ]; then
      KLIB_SAP_SA_logmsg INFO 120 6 sapsa.cat "INFO: Local Configuration tuning for \"%1\$s\"." $INSTANCE

      # export value to VG as "LOCAL" to be updated in metadata for reference during DNP.
      VOLUME_GROUPS="LOCAL"

        if [ $SERVICE_NETWORK == "LOCAL" ]; then       
            clmgr modify resource_group $rgname \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?

        else
            clmgr modify resource_group $rgname \
                SERVICE_LABEL="$SERVICE_LABEL" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?
        fi
    else
        if [ $SERVICE_NETWORK == "LOCAL" ]; then       
        KLIB_SAP_SA_logmsg INFO 120 6 sapsa.cat "INFO: Local Configuration tuning for \"%1\$s\"." $INSTANCE

        #export service ip to be "LOCAL" to be updated in metadata for reference during DNP.
        SERVICE_LABEL=LOCAL

            clmgr modify resource_group $rgname \
                VOLUME_GROUP="$VOLUME_GROUPS" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?

        else
		# Handle case - Pure & dedicated configuration
		# final else part - free from local FS config and resources sharing.
    
            clmgr modify resource_group $rgname \
                SERVICE_LABEL="$SERVICE_LABEL" \
                VOLUME_GROUP="$VOLUME_GROUPS" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?

        fi
    fi

fi

    (( $rc != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
        clmgr -f delete application_monitor $appmonname
        clmgr -f delete application $appname
        clmgr -f delete resource_group $rgname
        InternalErrorAbort
    }
    
    # Add dependency for DataBase resource group
  	if [[ $DBRG != "NONE" ]] ; then 
        # check if $DBRG already has been defined in a START_AFTER relationship with existing $rgname.
        rglist=$(clodmget -n -f group_child -q "group_parent=$DBRG and dependency_type=START_AFTER" HACMPrgdependency)
        rg=$(echo $rgname)

        for listrg in $rglist
        do
             if [[ "$listrg" == "$rg" ]]
             then
                  IS_DEPENDENCY_DEFINED=TRUE
                  break
              fi
        done
    
        if [[ $IS_DEPENDENCY_DEFINED != "TRUE" ]]
        then

        KLIB_SAP_SA_logmsg INFO 120 7 sapsa.cat "INFO: Adding Dependency with \"%1\$s\"." $DBRG

        /usr/es/sbin/cluster/utilities/clmgr add dependency START=$rgname AFTER=$DBRG 2> /dev/null
        (( $? != 0 )) && {

            if [ $SERVICE_NETWORK != "LOCAL" ]; then
                /usr/es/sbin/cluster/utilities/clmgr -f delete service_ip $SERVICE_LABEL
            fi
            /usr/es/sbin/cluster/utilities/clmgr -f delete resource_group $rgname
            /usr/es/sbin/cluster/utilities/clmgr -f delete resource_group $DBRG
            /usr/es/sbin/cluster/utilities/clmgr -f delete application_monitor $appmonname
            /usr/es/sbin/cluster/utilities/clmgr -f delete application $appname

        }
        fi
       fi
    # Associate the application with the resource group
if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]] 
then

    claddsaapp -a $APP_ID \
        RESOURCE_GROUP="$rgname" \
        SAPSYSTEMNAME="$SAPSYSTEMNAME" \
        INSTANCE_NAMES="$INSTANCE" \
        INSTANCE_NUMBERS="$INSTANCE_NO" \
        VIRTUAL_IPS="$SERVICE_LABEL" \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        APPLICATION_NAME="$APP_ID" \
        VOLUME_GROUP="$VOLUME_GROUPS" \
        SERVICE_NETWORK="$SERVICE_NETWORK" \
        PROFILE="$PROFILE" \
        EXECUTABLE="$SAP_INSTANCE_EXE" \
        START_TIMEOUT="60" \
        START_DELAY="0" \
        STOP_TIMEOUT="10" \
        STOP_DELAY="0" \
        NOTIFICATION_LEVEL="0" \
        SA_SAP_XPLATFORM_LOGGING="0" \
        EC_START_FAILED="1" \
        EC_START_SERVICE_FAILED="1" \
        EC_START_NFS_FAILED="1" \
        EC_MONITOR_SAPSTARTSRV_UNAVAILABLE="1" \
        EC_MONITOR_FAILOVER_ON_GW_OUTAGE="0" \
        ENS_SYNC="10" \
        IS_ERS_ENABLED="0"


    (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
    }

else

    claddsaapp -a $APP_ID \
        SAPSYSTEMNAME="$SAPSYSTEMNAME" \
        INSTANCE_NAMES="$INSTANCE" \
        INSTANCE_NUMBERS="$INSTANCE_NO" \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        PROFILE="$PROFILE" \
        EXECUTABLE="$SAP_INSTANCE_EXE" \
        START_TIMEOUT="60" \
        START_DELAY="0" \
        STOP_TIMEOUT="10" \
        STOP_DELAY="0" \
        NOTIFICATION_LEVEL="0" \
        SA_SAP_XPLATFORM_LOGGING="0" \
        EC_START_FAILED="1" \
        EC_START_SERVICE_FAILED="1" \
        EC_START_NFS_FAILED="1" \
        EC_MONITOR_SAPSTARTSRV_UNAVAILABLE="1" \
        EC_MONITOR_FAILOVER_ON_GW_OUTAGE="0" \
        ENS_SYNC="10" \
        IS_ERS_ENABLED="0"



    (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
    }

    if [[ "$IS_IP_REUSED" == "TRUE"  && "$IS_VG_REUSED" != "TRUE" ]]
    then
        print "HACMPsa_metadata: value = $VOLUME_GROUPS " | odmchange  -o HACMPsa_metadata -q  "application_id=$APP_ID and name=VOLUME_GROUP"
       (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
       }
    fi

    if [[  "$IS_VG_REUSED" == "TRUE" &&  "$IS_IP_REUSED" != "TRUE"  ]]
    then
       print "HACMPsa_metadata: value = $SERVICE_LABEL " | odmchange  -o HACMPsa_metadata -q  "application_id=$APP_ID and name=VIRTUAL_IPS"
       (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
       }
    fi
fi

    #Adding DBRG information to HACMPsa_metadata ODM.
    if [[ $DBRG != "NONE" && $IS_DEPENDENCY_DEFINED != "TRUE" ]]
    then
         claddsaapp -a $APP_ID \
         DBRG="$DBRG"

    (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
    }
   fi 

    # Discover GFS related global variables
    KLIB_SAP_SA_logmsg INFO 120 10 sapsa.cat "INFO: Discovering NFS information."

    NFS_COUNT=$(mount | awk '$4~ /nfs/ { print $3} ' | awk '$1~ /sapmnt/ { print $1}' | wc -l )
    if (( $NFS_COUNT > 0 ))
    then
          IS_NFS=1
          NFS_IP=$(mount | awk '$4~ /nfs/' | grep -w $SAPSID | awk '{print $1 }')
          SAPMNT_NFS=$(mount | awk '$4~ /nfs/' | grep -w $SAPSID | awk '{print $2 }')
    else
          IS_NFS=0
    fi	

    # Add the SAP Globals if it doesn't exists
    KLIB_SAP_SA_logmsg INFO 120 11 sapsa.cat "INFO: Updating SAP GLOBALS."
    SAP_GLOBALS=$( echo $SAP_GLOBALS"_"$SAPSYSTEMNAME )
    
    out=$(odmget -q "application_id=$SAP_GLOBALS"  HACMPsa_metadata | grep $SAP_GLOBALS)
    (( $? != 0 )) && {
        claddsaapp -a $SAP_GLOBALS \
            IS_NFS="$IS_NFS" \
            EXPORTS="$SAPMNT_NFS" \
            NFS_IP="$NFS_IP" \
	    NOTIFY="" \
            SAPADMUSER="$SAPADMNUSR" \
            SAPENV="env LANG=C " \
            LOGGER_LOGFILE="/var/hacmp/log/SAPutils.log" \
            OSCON_OnOff_APP="1" \
            OSCON_OnOff_CS="1" \
            OSCON_OnOff_ERS="1" 

    }

   #Update Settling Time to 120 seconds.
   SETTLE_TIME=$(/usr/es/sbin/cluster/utilities/clodmget -n  -f settling_time HACMPcluster)
    if (( $SETTLE_TIME < 120 ))
    then
        /usr/es/sbin/cluster/utilities/clsettlingtime change '120'
    fi

    #Update HACMPsap_connector ODM for connector script to handle Admin Start/Stop operations
     addConnectorMetaData -a $APP_ID \
         INSTANCE_NUMBERS="$INSTANCE_NO" \
         RESOURCE_GROUP="$rgname" \
         SAPSYSTEMNAME="$SAPSYSTEMNAME" \
         SAP_HA_GLUE_CODE=0 \
         STABILIZATION_INTERVAL="$STAB_INT" \
         IS_ERS_ENABLED=0 \
         END_STABLE_TIME=0

    cltopinfo
    KLIB_SAP_SA_logmsg INFO 120 12 sapsa.cat "INFO: Successfully configured instance \"%1\$s\" with application \"%2\$s\"." $INSTANCE $APP_ID
    return $?
}
#----------------------------------------------------------------------------
# Function:
#   addSAPERSInstance
#
# Purpose:
#   To Create HACMP resources and resource group for managing SAP Enqueue 
#   Replication Server Instance(s). There may be two ERS instances running in 
#   a given SAP system, however, HACMP manages both of them in a single 
#   resource group.
#
# Arguments:
#   None.
#
# Returns:
#   0 For sucess
#   1 For failure
#----------------------------------------------------------------------------

function addSAPERSInstance {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset instances instance_nos output scs_nos out rglist rg
    typeset sap_scs_appid sap_scs_name str1 str2 myout
    typeset sap_scs_vip scs_ip1 scs_ip2 sap_scs_ip1 sap_scs_ip2 sap_scs_ip
    typeset -A hostnames scs_nodes
    typeset -L64 APP_ID=$APPLICATION_ID
    typeset -L64 rgname=$(echo "SAP_"$SAPSID"_"$INSTANCE"_RG")
    typeset -L64 appname=$(echo $SAPSID"_"$INSTANCE"_AP")
    typeset -L64 appmonname=$(echo $SAPSID"_"$INSTANCE"_AM")
    typeset -L64 ers_rel_mon=$(echo $SAPSID"_"$INSTANCE"_REL_MON")
    typeset -L64 GSA_APP=$(echo "SAP_"$SAPSID"_GFS")
    typeset -i count
    typeset -i STAB_INT=240
    typeset gfs_nodes SCS_NODES
    typeset instance_profile instance_num local_node_name startup_profile
    typeset instance_start_profile inst_profile SAPSCSRG
    typeset -A myvar
    typeset sap_scs_appid
    typeset scs_nos
    typeset -i profile_found=0
    typeset -i exe_found=0
    typeset -i ip_found=0
    typeset profile_file
    local_node_name=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
    COMPONENT_ID="SAPNW_ERSINSTANCE"
    IS_RESOURCE_REUSED="FALSE"
    IS_IP_REUSED="FALSE"
    IS_VG_REUSED="FALSE"
    IS_DEPENDENCY_DEFINED="FALSE"
    SAP_GLOBALS="SAP_GLOBALS"

    #Adding Discovered SAP ERS instances to HACMP configuration
    KLIB_SAP_SA_logmsg INFO 40 11 sapsa.cat "Adding Discovered SAP ERS instances: %s to PowerHA SystemMirror configuration.\n" $INSTANCE
 
    rgname=$(getUnusedName $rgname "resource_group")
    appname=$(getUnusedName $appname "application")
    appmonname=$(getUnusedName $appmonname "application_monitor")
    ers_rel_mon=$(getUnusedName $ers_rel_mon "application_monitor")
    profile_file=$( cat /usr/sap/sapservices | grep -w $SAPSID | grep ERS | awk '{print $5}' | awk -F "=" '{print $2}')

    KLIB_SAP_SA_logmsg INFO 30 40 sapsa.cat "Please follow below steps after successful addition of ERS instance to avoid false ERS restart. \n"
    KLIB_SAP_SA_logmsg INFO 30 41 sapsa.cat "If ERS need to be configured with PowerHA , Edit the file %s with below changes.\n" $profile_file
    KLIB_SAP_SA_logmsg INFO 30 42 sapsa.cat "1.Comment the line containing Autostart = 1 \n"
    KLIB_SAP_SA_logmsg INFO 30 43 sapsa.cat "2. Edit the line Restart_Program_00 by replacing Restart_Program_00 as Start_Program_00 \n"

    # check if instance has already been added
    /usr/es/sbin/cluster/utilities/clodmget -n -q "name=INSTANCE_NUMBERS" -f value HACMPsa_metadata | while read line
    do
       # check if the instance is already configured to PHA
       if [[ $line == $INSTANCE_NO ]]
       then
            KLIB_SAP_SA_logmsg ERROR 120 1 sapsa.cat "ERROR: SAP Instance \"%1\$s\" is already configured to be highly available through PowerHA SM. Exiting." $INSTANCE 
            exit 1;
       fi
    done

    setSAPGlobalEnv $SAPSID
    ret=$?
    (( $ret != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 2 sapsa.cat "Unexpected error encountered while attempting to create resource group: %s\n" $rgname
        InternalErrorAbort
    }

    #check if the profiles exists and the instance numbers are correct.

      # Set START_PROFILE
                instance_start_profile=$SAPPROFILEDIR"/START_"$INSTANCE"_"$SERVICE_LABEL

      # Set INSTANCE_PROFILE
                inst_profile=$SAPPROFILEDIR"/"$SAPSID"_"$INSTANCE"_"$SERVICE_LABEL

       if [ -f ${instance_start_profile} ]; then
          instance_profile=${instance_start_profile};
       else
          instance_profile=${inst_profile};
      fi

        [[ ! -f $instance_profile ]] && {
            KLIB_SAP_SA_logmsg ERROR 30 23 sapsa.cat "Unable to find Startup profile %s for instance %s\n" $instance_profile $INSTANCE
            InternalErrorAbort
        }
        instance_num=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C $SAPEXEDIR/sappfpar \
                      pf=$instance_profile SAPSYSTEM" 2>/dev/null)
        (( $instance_num != $INSTANCE_NO )) && {
            KLIB_SAP_SA_logmsg ERROR 30 24 sapsa.cat "Discovered instance number for instance %s is not matching.Possible wrong instance startup profile %s.\n" $INSTANCE $instance_profile
            InternalErrorAbort
        }
        for node in $PARTICIPATING_NODES;do

            output=$(cl_rsh $node "/usr/bin/su - $SAPADMNUSR -c \"env LANG=C  \
                      sapcontrol -nr $INSTANCE_NO -function ParameterValue SCSID\"" 2>/dev/null \
                         | egrep -v "OK|ParameterValue|[0-9] " )
            if [[ -z $output ]];then
                continue
            else
                if [[ ! $(echo $output | grep "NIECONN_REFUSED" ) ]];then
                     scs_nos=$(echo $output | sed 's/^[ \t]*//;s/[ \t]*$//')
                     break;
                fi
           fi
        done

    sap_scs_appid=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=INSTANCE_NUMBERS and value=\"${scs_nos}\"" -f application_id HACMPsa_metadata)
    [[ -z $sap_scs_appid ]] && {
        KLIB_SAP_SA_logmsg ERROR 30 28 sapsa.cat "Unable to find SAP SCS instance resources configured on the cluster. Please configure SAP SCS instances using Smart Assist for SAP.\n"
        InternalErrorAbort
    }

 SCS_NODES=$(getNodes $sap_scs_appid)
 typeset -i k=0
 for i in $SCS_NODES
 do 
    scs_nodes[$k]=$i
    ((k=$k+1))
 done
   if [[ ${participating_nodes[0]} == ${scs_nodes[0]} ]];then
        typeset temp
        temp=${participating_nodes[0]}
        typeset -i p
        p=$pcount-1
        participating_nodes[0]=${participating_nodes[$p]}
        participating_nodes[$p]=$temp
    fi

  for node in $PARTICIPATING_NODES
  do

     PROFILE=$(cl_rsh $node "/usr/bin/su - $SAPADMNUSR -c \"env LANG=C  \
         sapcontrol -nr $instance_num \
         -function ParameterValue SAPPROFILE -format script \"" 2>/dev/null \
          | grep "^0 :" | cut -f2 -d :)

    if [[ -n $PROFILE ]]
      then
        profile_found=1
        SAP_INSTANCE_EXE=$(cl_rsh $node "/usr/bin/su - $SAPADMNUSR -c \"env LANG=C  \
           sapcontrol -nr $instance_num \
           -function ParameterValue DIR_EXECUTABLE -format script \"" 2>/dev/null \
           | grep "^0 :" | cut -f2 -d :)

          if [[ -n $SAP_INSTANCE_EXE ]]
          then
               exe_found=1
               break
          fi
     fi
 done

 if (( $profile_found == 0 ))
   then
        KLIB_SAP_SA_logmsg ERROR 60 7 sapsa.cat "ERROR: %s : No output from sapcontrol for process status\n" $PROGRAM
        exit 1
 fi

 if (( $exe_found == 0 ))
   then
            KLIB_SAP_SA_logmsg ERROR 60 7 sapsa.cat "ERROR: %s : No output from sapcontrol for process status\n" $PROGRAM
            exit 1
 fi



    KLIB_SAP_SA_logmsg INFO 120 8 sapsa.cat "INFO: SAP Instance \"%1\$s\" EXE directory is \"%2\$s\" ." $INSTANCE $SAP_INSTANCE_EXE
    KLIB_SAP_SA_logmsg INFO 120 9 sapsa.cat "INFO: SAP Instance \"%1\$s\" Profile is \"%2\$s\"." $INSTANCE $PROFILE


if [[ $VOLUME_GROUPS != "LOCAL" ]] ; then
    isVGsAlreadyDefined VOLUME_GROUPS
    if (( $? == 1 ))
    then
        # It  means the VG is already defined to SM. so set following variable to TRUE
        IS_RESOURCE_REUSED=TRUE
        IS_VG_REUSED=TRUE

         #The code should proceed by grouping the current instance to the RG to which resource has already been defined.
         RG_OF_THE_VG=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=VOLUME_GROUP and value=$VOLUME_GROUPS" -f group HACMPresource)
         rgname=$RG_OF_THE_VG
         KLIB_SAP_SA_logmsg INFO 120 2 sapsa.cat "INFO: Since the VG \"%1\$s\" seems to be already defined as a resource to PowerHA SM, the instance \"%2\$s\" will be grouped with the Resource Group \"%3\$s\"." $VOLUME_GROUPS $INSTANCE $rgname

         # get the app_ID of this RG from HACMPsa_metadata , if there is no app_ID in metadata, then add entries in HACMPsa_metadata with new APP_NAME}
         APP_NAME=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=RESOURCE_GROUP and value=$rgname" -f application_id HACMPsa_metadata)
         if [[ -n $APP_NAME ]]
         then
              APP_ID=$APP_NAME
              KLIB_SAP_SA_logmsg INFO 120 3 sapsa.cat "INFO: Please note that the instance \"%1\$s\" will be grouped with RG \"%2\$s\" of Application \"%3\$s\"." $INSTANCE $rgname $APP_ID
         fi
    fi
fi

    if [[ $SERVICE_NETWORK != "LOCAL" ]] ; then
        isServiceIPLabelAlreadyDefined $SERVICE_LABEL
        if (( $? == 1 ))
        then
           # this means the service_ip is already defined to PHA . so set following variable to TRUE
           IS_RESOURCE_REUSED=TRUE
           IS_IP_REUSED=TRUE

           #The code should proceed by grouping the current instance to the RG to which resource has already been defined.
           RG_OF_THE_SERVICE_IP=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=SERVICE_LABEL and value=$SERVICE_LABEL" -f group HACMPresource)

           # Now this will become the rgname for new instance as well.
           rgname=$RG_OF_THE_SERVICE_IP
           KLIB_SAP_SA_logmsg INFO 120 4 sapsa.cat "INFO: Since the Service IP label seems to be already defined as a resource to PowerHA SM, The instance \"%1\$s\"  will be grouped with the Resource Group \"%2\$s\"." $INSTANCE $rgname

           # get the app_ID of this RG from HACMPsa_metadata , if there is no app_ID in metadata, then add entries in HACMPsa_metadata with new APP_NAME}
           APP_NAME=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=RESOURCE_GROUP and value=$rgname" -f application_id HACMPsa_metadata)
           if [[ -n $APP_NAME ]]
           then
                APP_ID=$APP_NAME
                KLIB_SAP_SA_logmsg INFO 120 3 sapsa.cat "INFO: Please note that the instance \"%1\$s\" will be grouped with RG \"%2\$s\" of Application \"%3\$s\"." $INSTANCE $rgname $APP_ID
           fi
        fi

    fi


   sap_scs_name=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=INSTANCE_NAMES and application_id=$sap_scs_appid" -f value HACMPsa_metadata)
    [[ -z $sap_scs_name ]] && {
        KLIB_SAP_SA_logmsg ERROR 30 28 sapsa.cat "Unable to find SAP SCS instance resources configured on the cluster. Please configure SAP SCS instances using Smart Assist for SAP.\n"
        InternalErrorAbort
    }

    sap_scs_name=$(echo $sap_scs_name | awk '{gsub(" ","_");print $0}')

    SAPSCSRG=$(/usr/es/sbin/cluster/utilities/clodmget -n -q  "name=RESOURCE_GROUP and application_id=$sap_scs_appid" -f value HACMPsa_metadata)
    sap_scs_vip=$(/usr/es/sbin/cluster/utilities/clmgr -a SERVICE_LABEL query RG $SAPSCSRG | awk -F "=" '{print $2}'| sed s/\"//g)
    sap_scs_vip=$(echo $sap_scs_vip | awk '{gsub(" ","_");print $0}')

    scs_ip1=$(echo $sap_scs_vip | cut -f1 -d_)
    sap_scs_ip1=$(LC_ALL=C host $scs_ip1 2> /dev/null | cut -d, -f1 | cut -d' ' -f3)
    scs_ip2=$(echo $sap_scs_vip | cut -f2 -d_)
    sap_scs_ip2=$(LC_ALL=C host $scs_ip2 2> /dev/null | cut -d, -f1 | cut -d' ' -f3)
    if [[ $sap_scs_ip1 == $sap_scs_ip2 ]]
    then
          sap_scs_ip="$sap_scs_ip1"
    else
          sap_scs_ip="$sap_scs_ip1 $sap_scs_ip2"
          sap_scs_ip=$(echo $sap_scs_ip | awk '{gsub(" ","_");print $0}')
   fi

    # Update IS_ERS_ENABLED attribute
    print "HACMPsa_metadata: value = 1 "| odmchange  -o HACMPsa_metadata -q  "application_id=$sap_scs_appid and name=IS_ERS_ENABLED"

    # Update IS_ERS_ENABLED attribute
    print "HACMPsap_connector: value = 1 "| odmchange  -o HACMPsap_connector -q  "application_id=$sap_scs_appid and name=IS_ERS_ENABLED"

  # Handle case : Parent ASCS instances are grouped 
	count=$(/usr/es/sbin/cluster/utilities/clodmget -n -q  "application_id=$sap_scs_appid and name=INSTANCE_NUMBERS" -f value HACMPsa_metadata | wc -l )		
	if (( $count > 1 ))
	then
		 # This means the parent is grouped with some other instance
		 # get exisiting entries in MISC_DATA
                 PARENT_RG=$(/usr/es/sbin/cluster/utilities/clodmget -n -q  "application_id=$sap_scs_appid and name=RESOURCE_GROUP" -f value HACMPsa_metadata)
		 EXISTING_MISC_DATA=$(/usr/es/sbin/cluster/utilities/clmgr -a  MISC_DATA query RG $PARENT_RG| awk -F "=" '{print $2}'| sort -u | sed s/\"//g)
		 if [[ -n $EXISTING_MISC_DATA ]]
                 then
		     IS_ERS_GROUPED=TRUE
		     # parse "$EXISTING_MISC_DATA" and get the first ERS instance number
		     PRI_ERS=$(echo $EXISTING_MISC_DATA | awk -F "_" '{print $1}')
		     PRI_ERS_NO=${PRI_ERS##${PRI_ERS%%??}}
		     # Now get the application id of this ERS , to which the current instance would have to be grouped.
		      APP_NAME=$(/usr/es/sbin/cluster/utilities/clodmget -n -q  "name=INSTANCE_NUMBERS and value=$PRI_ERS_NO" -f application_id HACMPsa_metadata)
                     if [[ -n $APP_NAME ]]
                     then
                           IS_RESOURCE_REUSED=TRUE
                           APP_ID=$APP_NAME
		           rgname=$(/usr/es/sbin/cluster/utilities/clodmget -n -q  "name=RESOURCE_GROUP and application_id=$APP_NAME" -f value HACMPsa_metadata)
                     else
                           #We are at this case because some parent (A)SCS instances were found without any ERS application defined 
                           #But  some MISC_DATA was left in parent RG information. This might be because of ERS application removal without parent instance being intimated. 
                           #So have to clear the erroneous MISCDATA in parent
                            EXISTING_MISC_DATA=" "             
                     fi
                 fi
                ERS_MISC_DATA=$(echo $sap_scs_name","$sap_scs_ip)
	fi	 
        ERS_MISC_DATA=$(echo $sap_scs_name","$sap_scs_ip)

    #check if we have SAP global file system configured.
    SAPGFSAPPID=$( /usr/es/sbin/cluster/utilities/clodmget -n -q "name=APPLICATION_NAME and application_id=$GSA_APP" -f value HACMPsa_metadata)
    [[ -z $SAPGFSAPPID ]] && {
        KLIB_SAP_SA_logmsg WARN 30 39 sapsa.cat "WARNING: Did not discover Smart Assist enabled NFSv4 SAP Global File System.\n\
                           Continuing on the assumption that administrator has used alternate \
                           methods (GPFS, NFS in another cluster etc) to setup highly available \
                           SAP Global File System. \n"
    } || {   
    
         #check, if the participating nodes are SAP GFS ready?
         gfs_nodes=$(getNodes $SAPGFSAPPID)
         for node in $PARTICIPATING_NODES; do
            KLIB_UTIL_LIST_is_in_list gfs_nodes $node || {
            KLIB_SAP_SA_logmsg ERROR 30 26 sapsa.cat "SAP Global File system is not configured on %s node where %s has been selected to run.\n"$node $INSTANCE
            InternalErrorAbort
           }
        done
   }

    
    #check, if the participating nodes are SAP SCS ready?
    #ERS instances must run only on nodes where SCS instances are configured to run
    typeset ers_scs_nodes
    ers_scs_nodes=$(getNodes $sap_scs_appid)
    for node in $PARTICIPATING_NODES; do
            KLIB_UTIL_LIST_is_in_list ers_scs_nodes $node || {
                KLIB_SAP_SA_logmsg ERROR 30 29 sapsa.cat "SAP SCS instance(s) is/are not configured on %s node where %s has been selected to run.\
                Participating node list must match the node list of SCS instances.\n" $node $INSTANCE
                InternalErrorAbort
          }
    done
    
    #If the IP is not node bound then Check it is an aliased IP or not?
   for node in $PARTICIPATING_NODES
   do
    if [[ $SERVICE_NETWORK != "LOCAL" ]] ; then
          
            cl_rsh $node "/usr/es/sbin/cluster/sa/sap/sbin/cl_checkIsAliasAddr $SERVICE_LABEL"
               if [[ $? == 0 ]];then
                   ip_found=1
                   break
               fi
    fi
   done
  if [[ $ip_found == 0 ]];then
            KLIB_SAP_SA_logmsg ERROR 30 44 sapsa.cat "The IP address \"%1\$s\" specified for SAP Instance \"%2\$s\" must be configured as an alias IP address on any one of the nodes participating in this instance." $SERVICE_LABEL $INSTANCE
            InternalErrorAbort
  fi

  if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]]
  then
    #Creating Resource Group for managing SCS instances
    KLIB_SAP_SA_logmsg INFO 40 12 sapsa.cat "Adding %s Resource Group to support SAP ERS instances: %s\n" $rgname $INSTANCE

    clmgr add resource_group "$rgname" \
        PRIMARYNODES="${participating_nodes[*]}" \
        STARTUP="OHN" \
        FALLBACK="NFB" \
        FALLOVER="FNPN" || {
            KLIB_SAP_SA_logmsg ERROR 30 2 sapsa.cat "Unexpected error encountered while attempting to create resource group: %s\n" $rgname
            InternalErrorAbort
        }
  fi

  if [[ "$SERVICE_NETWORK" != "LOCAL" ]]; then

    if [[ "$IS_IP_REUSED" == "FALSE" ]]; then
        addServiceIPLabel
    fi
  fi


  if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]]
  then

    # Creating application controller ...
    KLIB_SAP_SA_logmsg INFO 40 19 sapsa.cat "\tCreating PowerHA SystemMirror application controller: %s\n" $appname

    startscript="$SAPSA_SBIN/cl_sapStart -a $APP_ID"
    stopscript="$SAPSA_SBIN/cl_sapStop -a $APP_ID"


    clmgr add application $appname \
    STARTSCRIPT="$startscript" \
    STOPSCRIPT="$stopscript" \
    STARTUP_MODE="foreground"
    
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 46 sapsa.cat "Unexpected error encountered while attempting to create PowerHA SystemMirror application controller: %s\n" $appname
        InternalErrorAbort
    }



    # Creating custom application monitor
     KLIB_SAP_SA_logmsg INFO 40 8 sapsa.cat "\tCreating PowerHA SystemMirror application monitor: %s\n" $appmonname

    claddappmon name=$appmonname \
        MONITOR_TYPE='user' \
        RESOURCE_TO_MONITOR=$appname \
        INVOCATION='longrunning' \
        FAILURE_ACTION='fallover' \
        RESTART_METHOD="$startscript" \
        CLEANUP_METHOD="$stopscript" \
        MONITOR_METHOD="$SAPSA_SBIN/cl_sapMonitor -a $APP_ID" \
        MONITOR_INTERVAL='60' \
        HUNG_MONITOR_SIGNAL='9' \
        STABILIZATION_INTERVAL="$STAB_INT" \
        RESTART_COUNT=3 \
        RESTART_INTERVAL=240 >/dev/null 2>&1

    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 5 sapsa.cat " Unexpected error encountered while attempting to create PowerHA SystemMirror application monitor: %s\n" $appmonname
        InternalErrorAbort
    }

    # Creating custom application monitor
     KLIB_SAP_SA_logmsg INFO 40 8 sapsa.cat "\tCreating PowerHA SystemMirror application monitor: %s\n" $ers_rel_mon

    claddappmon name=$ers_rel_mon \
        MONITOR_TYPE='user' \
        RESOURCE_TO_MONITOR=$appname \
        INVOCATION='longrunning' \
        FAILURE_ACTION='fallover' \
        RESTART_METHOD="$startscript" \
        CLEANUP_METHOD="$stopscript" \
        MONITOR_METHOD="$SAPSA_SBIN/cl_sapERSrelocateMonitor -a $APP_ID" \
        MONITOR_INTERVAL='60' \
        HUNG_MONITOR_SIGNAL='9' \
        STABILIZATION_INTERVAL="$STAB_INT" \
        RESTART_COUNT=0 \
        RESTART_INTERVAL=0 >/dev/null 2>&1

    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 5 sapsa.cat " Unexpected error encountered while attempting to create PowerHA SystemMirror application monitor: %s\n" $ers_rel_mon
        InternalErrorAbort
    }


  fi
   
## Handle case - Resources sharing
if [[ "$IS_RESOURCE_REUSED" == "TRUE" ]]
then
     EXISTING_ERS_MISC_DATA=$(/usr/es/sbin/cluster/utilities/clmgr -a  MISC_DATA query RG $rgname | awk -F "=" '{print $2}'| sort -u | sed s/\"//g)
     str1=$(echo $EXISTING_ERS_MISC_DATA | awk -F "," '{ print $1}')
     str2=$(echo $EXISTING_ERS_MISC_DATA | awk -F "," '{ print $2}')
     if [[ -z $str1 || -z $str2 ]]
     then
          ERS_MISC_DATA=$(echo $sap_scs_name","$sap_scs_ip)
     else
	 # update the ERS data only if, Parent's information is not already defined in the existing MISC_DATA
         myout=$(echo $EXISTING_ERS_MISC_DATA | grep $sap_scs_name)
          (( $? !=0 )) && { 
            ERS_MISC_DATA=$(echo $str1"_"$sap_scs_name","$str2"_"$sap_scs_ip)
           }
     fi

     if [[  "$IS_VG_REUSED" == "TRUE" ]]
     then
        current_serviceip=$SERVICE_LABEL
        EXISTING_SERVICE_LABELS=$(/usr/es/sbin/cluster/utilities/clmgr -a SERVICE_LABEL query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
        SERVICE_LABEL="$EXISTING_SERVICE_LABELS $SERVICE_LABEL"
        if [[ "$SERVICE_NETWORK" != "LOCAL" || "$IS_IP_REUSED" != "TRUE" ]]; then
		   KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
		   clmgr modify resource_group $rgname \
			  SERVICE_LABEL="$SERVICE_LABEL" \
			  VG_AUTO_IMPORT="false" \
			  MISC_DATA="$ERS_MISC_DATA"
		   rc=$?
        else
		   KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
		  clmgr modify resource_group $rgname \
			  VG_AUTO_IMPORT="false"
			  MISC_DATA="$ERS_MISC_DATA"
		  rc=$?
        fi

        (( $rc != 0 )) && { # Internal Error
             KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
            # delete service IP from existing RG.
             clmgr -f delete application_monitor $appmonname
             clmgr -f delete application $appname
             InternalErrorAbort
        }
        IS_ERS_RG_MODIFIED=TRUE
     else
       if [[ "$IS_IP_REUSED" == "TRUE"  ]]
       then
          current_vg=$VOLUME_GROUPS
          EXISTING_VGS=$(/usr/es/sbin/cluster/utilities/clmgr -a VOLUME_GROUP query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
          VOLUME_GROUPS="$EXISTING_VGS $VOLUME_GROUPS"
	      if [ $current_vg != "LOCAL" ]; then
		     KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
		     clmgr modify resource_group $rgname \
			    VOLUME_GROUP="$VOLUME_GROUPS" \
			    VG_AUTO_IMPORT="false" \
			    MISC_DATA="$ERS_MISC_DATA"
		     rc=$?
          else
             KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
             clmgr modify resource_group $rgname \
                MISC_DATA="$ERS_MISC_DATA"
             rc=$?
	      fi

          (( $rc != 0 )) && { # Internal Error
              KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
             # delete vg name from existing RG.
             clmgr -f delete application_monitor $appmonname
             clmgr -f delete application $appname
             InternalErrorAbort
           }
           IS_ERS_RG_MODIFIED=TRUE
       fi
     fi
     if [[ "$IS_ERS_GROUPED" == "TRUE" &&  "$IS_ERS_RG_MODIFIED" == "FALSE" ]]
     then
        current_vg=$VOLUME_GROUPS
        current_serviceip=$SERVICE_LABEL

        EXISTING_SERVICE_LABELS=$(/usr/es/sbin/cluster/utilities/clmgr -a SERVICE_LABEL query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
        SERVICE_LABEL="$EXISTING_SERVICE_LABELS $SERVICE_LABEL"

        EXISTING_VGS=$(/usr/es/sbin/cluster/utilities/clmgr -a VOLUME_GROUP query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
        VOLUME_GROUPS="$EXISTING_VGS $VOLUME_GROUPS"

        KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
            clmgr modify resource_group $rgname \
                SERVICE_LABEL="$SERVICE_LABEL" \
                MISC_DATA="$ERS_MISC_DATA" \
                VOLUME_GROUP="$VOLUME_GROUPS" \
                VG_AUTO_IMPORT="false"
             rc=$?

          (( $rc != 0 )) && { # Internal Error
             KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
             clmgr -f delete application_monitor $appmonname
             clmgr -f delete application $appname
             InternalErrorAbort
           }

      fi

else

    ## Handle case - Local File system / Network Configurations
    KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE

    if [ $VOLUME_GROUPS == "LOCAL" ]; then
        KLIB_SAP_SA_logmsg INFO 120 6 sapsa.cat "INFO: Local Configuration tuning for \"%1\$s\"." $INSTANCE

        # export value to VG as "LOCAL" to be updated in metadata for reference during DNP.
        VOLUME_GROUPS="LOCAL"

        if [ $SERVICE_NETWORK == "LOCAL" ]; then
            clmgr modify resource_group $rgname \
                MISC_DATA="$ERS_MISC_DATA" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?

        else
            clmgr modify resource_group $rgname \
                SERVICE_LABEL="$SERVICE_LABEL" \
                MISC_DATA="$ERS_MISC_DATA" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?
        fi
    else
        if [ $SERVICE_NETWORK == "LOCAL" ]; then
           KLIB_SAP_SA_logmsg INFO 120 6 sapsa.cat "INFO: Local Configuration tuning for \"%1\$s\"." $INSTANCE

           # export service ip to be "LOCAL" to be updated in metadata for reference during DNP.
           SERVICE_LABEL=LOCAL

            clmgr modify resource_group $rgname \
                VOLUME_GROUP="$VOLUME_GROUPS" \
                MISC_DATA="$ERS_MISC_DATA" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?
        else
                # Handle case - Pure & dedicated configuration
                # final else part - free from local FS config and resources sharing.

            clmgr modify resource_group $rgname \
                SERVICE_LABEL="$SERVICE_LABEL" \
                MISC_DATA="$ERS_MISC_DATA" \
                VOLUME_GROUP="$VOLUME_GROUPS" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
             rc=$?

        fi
    fi
	(( $rc != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
        clmgr -f delete application_monitor $appmonname
        clmgr -f delete application $appname
        clmgr -f delete resource_group $rgname
        InternalErrorAbort
     }
fi

    SAPSCSRG=$(/usr/es/sbin/cluster/utilities/clodmget  -q  "name=RESOURCE_GROUP and application_id=$sap_scs_appid" -f value HACMPsa_metadata)
    SAPSCSRG=${SAPSCSRG//\"/}
 
if [[ $IS_ERS_GROUPED == "FALSE" ]] 
then 
     /usr/es/sbin/cluster/utilities/clRGinfo $SAPSCSRG | grep -q ONLINE 2>&1 >/dev/null
     if [[ $? == 0 ]]
     then
        KLIB_SAP_SA_logmsg ERROR 120 22 sapsa.cat "The resource group %s must be offline in order to change a resource group's behavioral polices.\n" $SAPSCSRG
        clmgr -f delete application_monitor $appmonname
        clmgr -f delete application $appname
        clmgr -f delete resource_group $rgname
        InternalErrorAbort
    else

       #Configure SAP SCS instance to follow Adaptive failover.
       #Please note that, the SCS instances is ensure above that
       #it has been setup at this point of time.

       /usr/es/sbin/cluster/utilities/clchgrp -g $SAPSCSRG -S 'OFAN' -O 'FUDNP' -B 'NFB'

          (( $? != 0 )) && { # Internal Error
           KLIB_SAP_SA_logmsg ERROR 120 14 sapsa.cat "Unable to change Runtime policy for SAP_SCS_RG.\n"
           clmgr -f delete application_monitor $appmonname
           clmgr -f delete application $appname
           clmgr -f delete resource_group $rgname
            InternalErrorAbort
         }


         #360 is used as that's the max value for a config_too_long event to kick in
         clmgr modify resource_group $SAPSCSRG NODE_PRIORITY_POLICY=most \
             NODE_PRIORITY_POLICY_SCRIPT="/usr/es/sbin/cluster/sa/sap/sbin/cl_SCSFailoverNodeCheck"  \
             NODE_PRIORITY_POLICY_TIMEOUT=360 \
		 MISC_DATA="$INSTANCE"

          (( $? != 0 )) && { # Internal Error
          KLIB_SAP_SA_logmsg ERROR 120 14 sapsa.cat "Unable to change Runtime policy for SAP_SCS_RG.\n"
          clmgr -f delete application_monitor $appmonname
          clmgr -f delete application $appname
          clmgr -f delete resource_group $rgname

          InternalErrorAbort
          }
    fi
else
   if [[ -z $EXISTING_MISC_DATA ]] 
   then
        ERS_DATA=$INSTANCE	
   else
         ERS_DATA=$(echo $EXISTING_MISC_DATA"_"$INSTANCE)
   fi
    clmgr modify resource_group $SAPSCSRG MISC_DATA="$ERS_DATA"

    (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 14 sapsa.cat "Unable to change Runtime policy for SAP_SCS_RG.\n"
        clmgr -f delete application_monitor $appmonname
        clmgr -f delete application $appname
        clmgr -f delete resource_group $rgname
        InternalErrorAbort
    }
fi 	

    # Associate the application with the resource group

if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]]
then

    claddsaapp -a $APP_ID \
        RESOURCE_GROUP="$rgname" \
        SAPSYSTEMNAME="$SAPSYSTEMNAME" \
        INSTANCE_NAMES="$INSTANCE" \
        INSTANCE_NUMBERS="$INSTANCE_NO" \
        VIRTUAL_IPS="$SERVICE_LABEL" \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        APPLICATION_NAME="$APP_ID" \
        VOLUME_GROUP="$VOLUME_GROUPS" \
        SERVICE_NETWORK="$SERVICE_NETWORK" \
        PROFILE="$PROFILE" \
        EXECUTABLE="$SAP_INSTANCE_EXE" \
        START_TIMEOUT="60" \
        START_DELAY="0" \
        STOP_TIMEOUT="10" \
        STOP_DELAY="0" \
        NOTIFICATION_LEVEL="0" \
        SA_SAP_XPLATFORM_LOGGING="0" \
        EC_START_FAILED="1" \
        EC_START_SERVICE_FAILED="1" \
        EC_START_NFS_FAILED="1" \
        EC_MONITOR_SAPSTARTSRV_UNAVAILABLE="1" \
        EC_MONITOR_FAILOVER_ON_GW_OUTAGE="0" \
        ENS_SYNC="10" 

    (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 sapsa.cat "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror. \n" $APP_ID
        InternalErrorAbort
    }

else

    claddsaapp -a $APP_ID \
        SAPSYSTEMNAME="$SAPSYSTEMNAME" \
        INSTANCE_NAMES="$INSTANCE" \
        INSTANCE_NUMBERS="$INSTANCE_NO" \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        PROFILE="$PROFILE" \
        EXECUTABLE="$SAP_INSTANCE_EXE" \
        START_TIMEOUT="60" \
        START_DELAY="0" \
        STOP_TIMEOUT="10" \
        STOP_DELAY="0" \
        NOTIFICATION_LEVEL="0" \
        SA_SAP_XPLATFORM_LOGGING="0" \
        EC_START_FAILED="1" \
        EC_START_SERVICE_FAILED="1" \
        EC_START_NFS_FAILED="1" \
        EC_MONITOR_SAPSTARTSRV_UNAVAILABLE="1" \
        EC_MONITOR_FAILOVER_ON_GW_OUTAGE="0" \
        ENS_SYNC="10" 

    (( $? != 0 )) && { # Internal Error
          KLIB_SAP_SA_logmsg ERROR 120 13 sapsa.cat "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror. \n" $APP_ID
        InternalErrorAbort
    }

    if [[ "$IS_IP_REUSED" == "TRUE"  && "$IS_VG_REUSED" != "TRUE" ]]
    then
       print "HACMPsa_metadata: value = $VOLUME_GROUPS " | odmchange  -o HACMPsa_metadata -q  "application_id=$APP_ID and name=VOLUME_GROUP"
       (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
       }
    fi

    if [[  "$IS_VG_REUSED" == "TRUE" &&  "$IS_IP_REUSED" != "TRUE"  ]]
    then
      print "HACMPsa_metadata: value = $SERVICE_LABEL " | odmchange  -o HACMPsa_metadata -q  "application_id=$APP_ID and name=VIRTUAL_IPS"
       (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
       }
    fi
fi

    # Discover GFS related global variables
    KLIB_SAP_SA_logmsg INFO 120 10 sapsa.cat "INFO: Discovering NFS information"

    NFS_COUNT=$(mount | awk '$4~ /nfs/ { print $3} ' | awk '$1~ /sapmnt/ { print $1}' | wc -l )
    if (( $NFS_COUNT > 0 ))
    then
           IS_NFS=1
           NFS_IP=$(mount | awk '$4~ /nfs/' | grep -w $SAPSID | awk '{print $1 }')
           SAPMNT_NFS=$(mount | awk '$4~ /nfs/' | grep -w $SAPSID | awk '{print $2 }')
    else
           IS_NFS=0
    fi

    # Add the SAP Globals if it doesn't exists
    KLIB_SAP_SA_logmsg INFO 120 11 sapsa.cat "INFO: Updating SAP GLOBALS."

    SAP_GLOBALS=$( echo $SAP_GLOBALS"_"$SAPSYSTEMNAME )
    out=$(odmget -q "application_id=$SAP_GLOBALS"  HACMPsa_metadata | grep $SAP_GLOBALS)
    (( $? != 0 )) && {
        claddsaapp -a $SAP_GLOBALS \
            IS_NFS="$IS_NFS" \
            EXPORTS="$SAPMNT_NFS" \
            NFS_IP="$NFS_IP" \
            NOTIFY="" \
            SAPADMUSER="$SAPADMNUSR" \
            SAPENV="env LANG=C " \
            LOGGER_LOGFILE="/var/hacmp/log/SAPutils.log" \
            OSCON_OnOff_APP="1" \
            OSCON_OnOff_CS="1" \
            OSCON_OnOff_ERS="1" 
 
    }

   #Update Settling Time to 120 seconds.
   SETTLE_TIME=$(/usr/es/sbin/cluster/utilities/clodmget -n  -f settling_time HACMPcluster)
    if (( $SETTLE_TIME < 120 ))
    then
        /usr/es/sbin/cluster/utilities/clsettlingtime change '120'
    fi

    #Update HACMPsap_connector ODM for connector script to handle Admin Start/Stop operations
     addConnectorMetaData -a $APP_ID \
         INSTANCE_NUMBERS="$INSTANCE_NO" \
         RESOURCE_GROUP="$rgname" \
         SAPSYSTEMNAME="$SAPSYSTEMNAME" \
         SAP_HA_GLUE_CODE=0 \
         STABILIZATION_INTERVAL="$STAB_INT" \
         END_STABLE_TIME=0

    cltopinfo
    KLIB_SAP_SA_logmsg INFO 120 12 sapsa.cat "INFO: Successfully configured instance \"%1\$s\" with application \"%2\$s\"." $INSTANCE $APP_ID
    return $?

}

#----------------------------------------------------------------------------
# Function:
#   addSAPASInstance
#
# Purpose:
#   To Create HACMP resources and resource group for managing SAP Application 
#   Server Instance.
#
# Arguments:
#   None.
#
# Returns:
#   0 For sucess
#   1 For failure
#----------------------------------------------------------------------------

function addSAPASInstance {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset instances instance_nos out rglist rg
    typeset -L64 APP_ID=$APPLICATION_ID 
    typeset -L64 rgname=$(echo "SAP_"$SAPSID"_"$INSTANCE"_RG")
    typeset -L64 appname=$(echo $SAPSID"_"$INSTANCE"_AP")
    typeset -L64 appmonname=$(echo $SAPSID"_"$INSTANCE"_AM")
    typeset -L64 GSA_APP=$(echo "SAP_"$SAPSID"_GFS")
    typeset service_ips
    typeset -i count
    typeset -i instcount
    typeset gfs_nodes
    typeset -i STAB_INT=600
    typeset instance_profile instance_num local_node_name
    typeset instance_start_profile inst_profile
    local_node_name=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
    COMPONENT_ID="SAPNW_ASINSTANCE"
    IS_RESOURCE_REUSED="FALSE"
    IS_IP_REUSED="FALSE"
    IS_VG_REUSED="FALSE"
    IS_DEPENDENCY_DEFINED="FALSE"
    SAP_GLOBALS="SAP_GLOBALS"

    #Adding Discovered SAP AS instances to HACMP configuration
    KLIB_SAP_SA_logmsg INFO 40 9 sapsa.cat "Adding Discovered SAP AS instance: %s to PowerHA SystemMirror configuration.\n" $INSTANCE

    rgname=$(getUnusedName $rgname "resource_group")
    appname=$(getUnusedName $appname "application")
    appmonname=$(getUnusedName $appmonname "application_monitor")

    # Find all the instances.
    instcount=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=INSTANCE_NUMBERS and value=$INSTANCE_NO" -f value HACMPsa_metadata | wc -l| awk '{printf $1}' )
    (( instcount = instcount + 1 ))
    # Add the instance count to the end of APP_ID
    APP_ID=$(echo $APPLICATION_ID"_"$instcount)


    setSAPGlobalEnv $SAPSID
    ret=$?
    (( $ret != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 12 sapsa.cat "Unexpected error encountered while setting up SAP Global Environment.\n"
        InternalErrorAbort
    }

    #check if the profiles exists and the instance numbers are correct.
      # Set START_PROFILE
                instance_start_profile=$SAPPROFILEDIR"/START_"$INSTANCE"_"$SERVICE_LABEL

      # Set INSTANCE_PROFILE
                inst_profile=$SAPPROFILEDIR"/"$SAPSID"_"$INSTANCE"_"$SERVICE_LABEL

       if [ -f ${instance_start_profile} ]; then
          instance_profile=${instance_start_profile};
       else
          instance_profile=${inst_profile};
      fi

        [[ ! -f $instance_profile ]] && {
            KLIB_SAP_SA_logmsg ERROR 30 23 sapsa.cat "Unable to find Startup profile %s for instance %s\n" $instance_profile $INSTANCE
            InternalErrorAbort
        }
        instance_num=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C $SAPEXEDIR/sappfpar \
                      pf=$instance_profile SAPSYSTEM" 2>/dev/null)
        (( $instance_num != $INSTANCE_NO )) && {
            KLIB_SAP_SA_logmsg ERROR 30 24 sapsa.cat "Discovered instance number for instance %s is not matching.Possible wrong instance startup profile %s.\n" $INSTANCE $instance_profile
            InternalErrorAbort
        }

    PROFILE=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
         sapcontrol -nr $instance_num \
         -function ParameterValue SAPPROFILE -format script " 2>/dev/null \
      | grep "^0 :" | cut -f2 -d :)

    [[ -z $PROFILE ]] && {
         KLIB_SAP_SA_logmsg INFO 60 7 sapsa.cat "ERROR: %s : No output from sapcontrol for process status\n" $PROGRAM
        exit 1
    }

    SAP_INSTANCE_EXE=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
         sapcontrol -nr $instance_num \
         -function ParameterValue DIR_EXECUTABLE -format script " 2>/dev/null \
      | grep "^0 :" | cut -f2 -d :)

    [[ -z $SAP_INSTANCE_EXE ]] && {
        KLIB_SAP_SA_logmsg INFO 60 7 sapsa.cat "ERROR: %s : No output from sapcontrol for process status\n" $PROGRAM
        exit 1
    }


    KLIB_SAP_SA_logmsg INFO 120 8 sapsa.cat "INFO: SAP Instance \"%1\$s\" EXE directory is \"%2\$s\" ." $INSTANCE $SAP_INSTANCE_EXE
    KLIB_SAP_SA_logmsg INFO 120 9 sapsa.cat "INFO: SAP Instance \"%1\$s\" Profile is \"%2\$s\"." $INSTANCE $PROFILE

if [[ $VOLUME_GROUPS != "LOCAL" ]] ; then
    isVGsAlreadyDefined VOLUME_GROUPS
	if (( $? == 1 ))
    then
	# this means the VG is already defined to SM. so set following variable to TRUE
	IS_RESOURCE_REUSED=TRUE
	IS_VG_REUSED=TRUE

         #The code should proceed by grouping the current instance to the RG to which resource has already been defined.
         RG_OF_THE_VG=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=VOLUME_GROUP and value=$VOLUME_GROUPS" -f group HACMPresource)
	 rgname=$RG_OF_THE_VG
         KLIB_SAP_SA_logmsg INFO 120 2 sapsa.cat "INFO: Since the VG \"%1\$s\" seems to be already defined as a resource to PowerHA SM, the instance \"%2\$s\" will be grouped with the Resource Group \"%3\$s\"." $VOLUME_GROUPS $INSTANCE $rgname

	 # get the app_ID of this RG from HACMPsa_metadata , if there is no app_ID in metadata, then add entries in HACMPsa_metadata with new APP_NAME}
	 APP_NAME=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=RESOURCE_GROUP and value=$rgname" -f application_id HACMPsa_metadata)
	 if [[ -n $APP_NAME ]]
         then
              APP_ID=$APP_NAME
              KLIB_SAP_SA_logmsg INFO 120 3 sapsa.cat "INFO: Please note that the instance \"%1\$s\" will be grouped with RG \"%2\$s\" of Application \"%3\$s\"." $INSTANCE $rgname $APP_ID
         fi
    fi
fi
	
    if [[ $SERVICE_NETWORK != "LOCAL" ]] ; then
        isServiceIPLabelAlreadyDefined $SERVICE_LABEL
    	if (( $? == 1 ))
    	then
           # this means the service_ip is already defined to PHA . so set following variable to TRUE
           IS_RESOURCE_REUSED=TRUE
	   IS_IP_REUSED=TRUE

           #The code should proceed by grouping the current instance to the RG to which resource has already been defined.
	   RG_OF_THE_SERVICE_IP=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=SERVICE_LABEL and value=$SERVICE_LABEL" -f group HACMPresource)

           # Now this will become the rgname for new instance as well.
           rgname=$RG_OF_THE_SERVICE_IP

           KLIB_SAP_SA_logmsg INFO 120 4 sapsa.cat "INFO: Since the Service IP label seems to be already defined as a resource to PowerHA SM, The instance \"%1\$s\"  will be grouped with the Resource Group \"%2\$s\"." $INSTANCE $rgname

           # get the app_ID of this RG from HACMPsa_metadata , if there is no app_ID in metadata, then add entries in HACMPsa_metadata with new APP_NAME}
           APP_NAME=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=RESOURCE_GROUP and value=$rgname" -f application_id HACMPsa_metadata)
            if [[ -n $APP_NAME ]]
            then
                APP_ID=$APP_NAME
                KLIB_SAP_SA_logmsg INFO 120 3 sapsa.cat "INFO: Please note that the instance \"%1\$s\" will be grouped with RG \"%2\$s\" of Application \"%3\$s\"." $INSTANCE $rgname $APP_ID
            fi
          fi
    fi

  # Get the SAP GFS APP_ID
  SAPGFSAPPID=$(/usr/es/sbin/cluster/utilities/clodmget -n -q "name=APPLICATION_NAME and application_id=$GSA_APP" -f value HACMPsa_metadata)
  #check if we have SAP global file system configured.
  [[ -z $SAPGFSAPPID ]] && {
        KLIB_SAP_SA_logmsg WARN 30 39 sapsa.cat "WARNING: Did not discover Smart Assist enabled NFSv4 SAP Global File System.\n\
                           Continuing on the assumption that administrator has used alternate \
                           methods (GPFS, NFS in another cluster etc) to setup highly available \
                           SAP Global File System. \n"
    } || {    
    
        #check, if the primary and take over nodes are SAP GFS ready?
        gfs_nodes=$(getNodes $SAPGFSAPPID)
        for node in "$PRINODE $TAKENODE"; do
            KLIB_UTIL_LIST_is_in_list gfs_nodes $node || {
            KLIB_SAP_SA_logmsg ERROR 30 26 sapsa.cat "SAP Global File system is not configured on %s node where %s has been selected to run.\n"$node $INSTANCE
            InternalErrorAbort
            }
            done
    }
    
    #If the IP is not node bound then Check it is an aliased IP or not?
    if [[ $SERVICE_NETWORK != "LOCAL" ]] ; then 

        [[ "$local_node_name" == "$PRINODE" ]] && {
            cl_checkIsAliasAddr $SERVICE_LABEL
        } || {
            cl_rsh $PRINODE "/usr/es/sbin/cluster/sa/sap/sbin/cl_checkIsAliasAddr $SERVICE_LABEL"
        }
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 30 27 sapsa.cat "SAP Instance name: %s is configured to run on node %s with an IP %s which is found to be an a non aliased address.\n" $INSTANCE $PRINODE $SERVICE_LABEL
            InternalErrorAbort
        }
    fi
	
    if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]]
    then 
        #Creating Resource Group for managing SCS instances
        KLIB_SAP_SA_logmsg INFO 120 15 sapsa.cat "Adding %s Resource Group to support SAP AS instance: %s\n" $rgname $INSTANCE

        if  [[ $SERVICE_NETWORK == "LOCAL" ]]
        then 
            clmgr add resource_group "$rgname" \
                PRIMARYNODES="$PRINODE" \
                STARTUP="OFAN" \
                FALLBACK="NFB" \
                FALLOVER="FNPN" || {
                    KLIB_SAP_SA_logmsg ERROR 30 2 sapsa.cat "Unexpected error encountered while attempting to create resource group: %s\n" $rgname
                    InternalErrorAbort
                }
            KLIB_SAP_SA_logmsg WARN 120 18 sapsa.cat "WARN: Since local IP configuration is detected, A single node RG would be created and the node preference would be ignored for %s" $INSTANCE
        else
            clmgr add resource_group "$rgname" \
                PRIMARYNODES="$PRINODE $TAKENODE" \
                STARTUP="OFAN" \
                FALLBACK="NFB" \
                FALLOVER="FNPN" || {
                    KLIB_SAP_SA_logmsg ERROR 30 2 sapsa.cat "Unexpected error encountered while attempting to create resource group: %s\n" $rgname
                    InternalErrorAbort
                }  
        fi
    fi

    if [[ "$SERVICE_NETWORK" != "LOCAL" ]]; then
        if [[ "$IS_IP_REUSED" == "FALSE" ]]; then
            addServiceIPLabel
        fi
    fi

  if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]]
  then

    # Creating application controller ...
    KLIB_SAP_SA_logmsg INFO 40 19 sapsa.cat "\tCreating PowerHA SystemMirror application controller: %s\n" $appname

    startscript="$SAPSA_SBIN/cl_sapStart -a $APP_ID"
    stopscript="$SAPSA_SBIN/cl_sapStop -a $APP_ID"


    clmgr add application $appname \
    STARTSCRIPT="$startscript" \
    STOPSCRIPT="$stopscript"    
    
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 46 sapsa.cat "Unexpected error encountered while attempting to create PowerHA SystemMirror application controller: %s\n" $appname
        InternalErrorAbort
    }

    # Creating custom application monitor
    KLIB_SAP_SA_logmsg INFO 40 8 sapsa.cat "\tCreating PowerHA SystemMirror application monitor: %s\n" $appmonname

    claddappmon name=$appmonname \
        MONITOR_TYPE='user' \
        RESOURCE_TO_MONITOR=$appname \
        INVOCATION='both' \
        FAILURE_ACTION='fallover' \
        RESTART_METHOD="$startscript" \
        CLEANUP_METHOD="$stopscript" \
        MONITOR_METHOD="$SAPSA_SBIN/cl_sapMonitor -a $APP_ID" \
        MONITOR_INTERVAL='60' \
        HUNG_MONITOR_SIGNAL='9' \
        STABILIZATION_INTERVAL="$STAB_INT" \
        RESTART_COUNT=3 \
        RESTART_INTERVAL=792 >/dev/null 2>&1

    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 30 5 sapsa.cat "Unexpected error encountered while attempting to create PowerHA SystemMirror application monitor: %s\n" $appmonname
        InternalErrorAbort
    }
   fi

## Handle case - Resources sharing
if [[ "$IS_RESOURCE_REUSED" == "TRUE" ]]
then

     if [[  "$IS_VG_REUSED" == "TRUE" ]]
     then
        current_serviceip=$SERVICE_LABEL
        EXISTING_SERVICE_LABELS=$(/usr/es/sbin/cluster/utilities/clmgr -a SERVICE_LABEL query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
        SERVICE_LABEL="$EXISTING_SERVICE_LABELS $SERVICE_LABEL"

	if [[ "$SERVICE_NETWORK" != "LOCAL" || "$IS_IP_REUSED" != "TRUE" ]]; then
		KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
		clmgr modify resource_group $rgname \
			SERVICE_LABEL="$SERVICE_LABEL" \
			VG_AUTO_IMPORT="false"
		rc=$?
	fi

          (( $rc != 0 )) && { # Internal Error
             KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
            # delete service IP from existing RG.
             clmgr -f delete application_monitor $appmonname
             clmgr -f delete application $appname
             InternalErrorAbort
           }
     else
       if [[ "$IS_IP_REUSED" == "TRUE"  ]]
       then
        current_vg=$VOLUME_GROUPS
        EXISTING_VGS=$(/usr/es/sbin/cluster/utilities/clmgr -a VOLUME_GROUP query RG $rgname | awk -F "=" '{print $2}'|sed s/\"//g)
        VOLUME_GROUPS="$EXISTING_VGS $VOLUME_GROUPS"

	if [ $current_vg != "LOCAL" ]; then
		KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE
		clmgr modify resource_group $rgname \
			VOLUME_GROUP="$VOLUME_GROUPS" \
			VG_AUTO_IMPORT="false"
		rc=$?    
	fi

          (( $rc != 0 )) && { # Internal Error
              KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
             # delete vg name from existing RG.
             clmgr -f delete application_monitor $appmonname
             clmgr -f delete application $appname
             InternalErrorAbort
           }
      fi
     fi
else 

    ## Handle case - Local File system / Network Configurations
    KLIB_SAP_SA_logmsg INFO 120 5 sapsa.cat "INFO: Modifying resource group \"%1\$s\" for Instance \"%2\$s\"." $rgname $INSTANCE

    if [ $VOLUME_GROUPS == "LOCAL" ]; then
     KLIB_SAP_SA_logmsg INFO 120 6 sapsa.cat "INFO: Local Configuration tuning for \"%1\$s\"." $INSTANCE

     # export value to VG as "LOCAL" to be updated in metadata for reference during DNP.
     VOLUME_GROUPS="LOCAL"

        if [ $SERVICE_NETWORK == "LOCAL" ]; then
            clmgr modify resource_group $rgname \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?

        else
            clmgr modify resource_group $rgname \
                SERVICE_LABEL="$SERVICE_LABEL" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?
        fi
    else
        if [ $SERVICE_NETWORK == "LOCAL" ]; then       
        KLIB_SAP_SA_logmsg INFO 120 6 sapsa.cat "INFO: Local Configuration tuning for \"%1\$s\"." $INSTANCE

        # export service ip to be "LOCAL" to be updated in metadata for reference during DNP.
        SERVICE_LABEL=LOCAL

            clmgr modify resource_group $rgname \
                VOLUME_GROUP="$VOLUME_GROUPS" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
             rc=$?

        else
		# Handle case - Pure & dedicated configuration
		# final else part - free from local FS config and resources sharing.
    
            clmgr modify resource_group $rgname \
                SERVICE_LABEL="$SERVICE_LABEL" \
                VOLUME_GROUP="$VOLUME_GROUPS" \
                VG_AUTO_IMPORT="false" \
                APPLICATIONS="$appname"
            rc=$?

        fi
    fi

fi

    (( $rc != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 30 17 sapsa.cat "Unexpected error encountered while attempting to modify resource group: %s\n" $rgname
        clmgr -f delete application_monitor $appmonname
        clmgr -f delete application $appname
        clmgr -f delete resource_group $rgname
        InternalErrorAbort
    }
    
    # Add dependency for DataBase resource group
    if [[ $DBRG != "NONE" ]] ; then 
        # check if $DBRG already has been defined in a START_AFTER relationship with existing $rgname.
        rglist=$(clodmget -n -f group_child -q "group_parent=$DBRG and dependency_type=START_AFTER" HACMPrgdependency)
        rg=$(echo $rgname)

        for listrg in $rglist
        do
             if [[ "$rg" == "$listrg" ]]
             then
                  IS_DEPENDENCY_DEFINED=TRUE
                  break
              fi
        done

        if [[ $IS_DEPENDENCY_DEFINED != "TRUE" ]]
        then

        KLIB_SAP_SA_logmsg INFO 120 7 sapsa.cat "INFO: Adding Dependency with \"%1\$s\"." $DBRG

        /usr/es/sbin/cluster/utilities/clmgr add dependency START=$rgname AFTER=$DBRG >> /dev/null
        (( $? != 0 )) && {

            if [ $SERVICE_NETWORK != "LOCAL" ]; then
                /usr/es/sbin/cluster/utilities/clmgr -f delete service_ip $SERVICE_LABEL
            fi
            /usr/es/sbin/cluster/utilities/clmgr -f delete resource_group $rgname
            /usr/es/sbin/cluster/utilities/clmgr -f delete resource_group $DBRG
            /usr/es/sbin/cluster/utilities/clmgr -f delete application_monitor $appmonname
            /usr/es/sbin/cluster/utilities/clmgr -f delete application $appname

        }
        fi
   fi

     # Associate the application with the resource group

if [[ "$IS_RESOURCE_REUSED" == "FALSE" ]] 
then

    claddsaapp -a $APP_ID \
        RESOURCE_GROUP="$rgname" \
        SAPSYSTEMNAME="$SAPSYSTEMNAME" \
        INSTANCE_NAMES="$INSTANCE" \
        INSTANCE_NUMBERS="$INSTANCE_NO" \
        VIRTUAL_IPS="$SERVICE_LABEL" \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        APPLICATION_NAME="$APP_ID" \
        VOLUME_GROUP="$VOLUME_GROUPS" \
        SERVICE_NETWORK="$SERVICE_NETWORK" \
        PROFILE="$PROFILE" \
        EXECUTABLE="$SAP_INSTANCE_EXE" \
        START_TIMEOUT="60" \
        START_DELAY="0" \
        STOP_TIMEOUT="10" \
        STOP_DELAY="0" \
        NOTIFICATION_LEVEL="0" \
        SA_SAP_XPLATFORM_LOGGING="0" \
        EC_START_FAILED="1" \
        EC_START_SERVICE_FAILED="1" \
        EC_START_NFS_FAILED="1" \
        EC_MONITOR_SAPSTARTSRV_UNAVAILABLE="1" \
        EC_MONITOR_FAILOVER_ON_GW_OUTAGE="0" \
        ENS_SYNC="10" 


    (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 sapsa.cat "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror. \n" $APP_ID
        InternalErrorAbort
    }

else

    claddsaapp -a $APP_ID \
        SAPSYSTEMNAME="$SAPSYSTEMNAME" \
        INSTANCE_NAMES="$INSTANCE" \
        INSTANCE_NUMBERS="$INSTANCE_NO" \
        SMARTASSIST_ID="$SMARTASSIST_ID" \
        COMPONENT_ID="$COMPONENT_ID" \
        PROFILE="$PROFILE" \
        EXECUTABLE="$SAP_INSTANCE_EXE" \
        START_TIMEOUT="60" \
        START_DELAY="0" \
        STOP_TIMEOUT="10" \
        STOP_DELAY="0" \
        NOTIFICATION_LEVEL="0" \
        SA_SAP_XPLATFORM_LOGGING="0" \
        EC_START_FAILED="1" \
        EC_START_SERVICE_FAILED="1" \
        EC_START_NFS_FAILED="1" \
        EC_MONITOR_SAPSTARTSRV_UNAVAILABLE="1" \
        EC_MONITOR_FAILOVER_ON_GW_OUTAGE="0" \
        ENS_SYNC="10" 

    (( $? != 0 )) && { # Internal Error
        KLIB_SAP_SA_logmsg ERROR 120 13 sapsa.cat "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror. \n" $APP_ID
        InternalErrorAbort
    }

    if [[ "$IS_IP_REUSED" == "TRUE"  && "$IS_VG_REUSED" != "TRUE" ]]
    then
        print "HACMPsa_metadata: value = $VOLUME_GROUPS " | odmchange  -o HACMPsa_metadata -q  "application_id=$APP_ID and name=VOLUME_GROUP"
        (( $? != 0 )) && { # Internal Error
	    KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
	    InternalErrorAbort
        }
    fi

    if [[  "$IS_VG_REUSED" == "TRUE" &&  "$IS_IP_REUSED" != "TRUE"  ]]
    then
        print "HACMPsa_metadata: value = $SERVICE_LABEL " | odmchange  -o HACMPsa_metadata -q  "application_id=$APP_ID and name=VIRTUAL_IPS" 
        (( $? != 0 )) && { # Internal Error
	    KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
	    InternalErrorAbort
        }
    fi
fi

    #Adding DBRG information to HACMPsa_metadata ODM.
    if [[ $DBRG != "NONE" && $IS_DEPENDENCY_DEFINED != "TRUE" ]]
    then
         claddsaapp -a $APP_ID \
         DBRG="$DBRG"

    (( $? != 0 )) && { # Internal Error
	KLIB_SAP_SA_logmsg ERROR 120 13 "ERROR:Unexpected error encountered while attempting to associate this application %s with PowerHA SystemMirror.\n"
        InternalErrorAbort
    }
    fi

    # Discover GFS related global variables
    KLIB_SAP_SA_logmsg INFO 120 10 sapsa.cat "INFO: Discovering NFS information"

    NFS_COUNT=$(mount | awk '$4~ /nfs/ { print $3} ' | awk '$1~ /sapmnt/ { print $1}' | wc -l )
    if (( $NFS_COUNT > 0 ))
    then
        IS_NFS=1
        NFS_IP=$(mount | awk '$4~ /nfs/' | grep -w $SAPSID | awk '{print $1 }')
        SAPMNT_NFS=$(mount | awk '$4~ /nfs/' | grep -w $SAPSID | awk '{print $2 }')
    else
	IS_NFS=0
    fi	

    # Add the SAP Globals if it doesn't exists
    KLIB_SAP_SA_logmsg INFO 120 11 sapsa.cat "INFO: Updating SAP GLOBALS."

    SAP_GLOBALS=$( echo $SAP_GLOBALS"_"$SAPSYSTEMNAME )

    out=$(odmget -q "application_id=$SAP_GLOBALS"  HACMPsa_metadata | grep $SAP_GLOBALS)
    (( $? != 0 )) && {
        claddsaapp -a $SAP_GLOBALS \
            IS_NFS="$IS_NFS" \
            EXPORTS="$SAPMNT_NFS" \
            NFS_IP="$NFS_IP" \
	    NOTIFY="" \
            SAPADMUSER="$SAPADMNUSR" \
            SAPENV="env LANG=C " \
            LOGGER_LOGFILE="/var/hacmp/log/SAPutils.log" \
            OSCON_LogLevel="0" \
            OSCON_OnOff_APP="1" \
            OSCON_OnOff_CS="1" \
            OSCON_OnOff_ERS="1" 

    }

    #Update Settling Time to 120 seconds.
    SETTLE_TIME=$(/usr/es/sbin/cluster/utilities/clodmget -n  -f settling_time HACMPcluster)
    if (( $SETTLE_TIME < 120 ))
    then
        /usr/es/sbin/cluster/utilities/clsettlingtime change '120'
    fi

    #Update HACMPsap_connector ODM for connector script to handle Admin Start/Stop operations
     addConnectorMetaData -a $APP_ID \
         INSTANCE_NUMBERS="$INSTANCE_NO" \
         RESOURCE_GROUP="$rgname" \
         SAPSYSTEMNAME="$SAPSYSTEMNAME" \
         SAP_HA_GLUE_CODE=0 \
         STABILIZATION_INTERVAL="$STAB_INT" \
         END_STABLE_TIME=0

    cltopinfo
    KLIB_SAP_SA_logmsg INFO 120 12 sapsa.cat "INFO: Successfully configured instance \"%1\$s\" with application \"%2\$s\"." $INSTANCE $APP_ID
    return $?
}

#----------------------------------------------------------------------------
# Function:
#   addServiceIPLabel
#
# Purpose:
#   Adds Service IP label to the HACMP configuration if
#   it doesn't already exist.
#
# Arguments:
#   n/a
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function addServiceIPLabel {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset results
    network=$SERVICE_NETWORK

    #
    # Can the service IP label be resolved?
    #
    /usr/bin/host $SERVICE_LABEL >/dev/null 2>&1
    (( $? != 0 )) && {
        # The service IP label cannot be resolved
        #user_msg 30 14 $SERVICE_LABEL
        KLIB_SAP_SA_logmsg ERROR 30 14 sapsa.cat "14 ERROR: The Service IP label: %s is not resolvable on the \
                          local system.  Please check to ensure the IP label is resolvable via either \
                          DNS, or /etc/hosts.\n" $SERVICE_LABEL
        exit 1
    }

    result=$(clmgr query interface | grep $SERVICE_LABEL)
    [[ -n $result ]] &&
        clmgr -f delete interface $SERVICE_LABEL

    result=$(clmgr query service_ip $SERVICE_LABEL 2>/dev/null)
    if [[ -z $result ]] 
    then
        KLIB_SAP_SA_logmsg INFO 40 2 sapsa.cat "\tCreating service IP label: %s\n" $SERVICE_LABEL

        typeset nodes="$PRINODE $TAKENODES"
        [[ -z $network ]] && {
              network=$(getServiceNetwork nodes)
        }

        clmgr add service_ip $SERVICE_LABEL \
            NETWORK=$network
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 30 16 sapsa.cat "Unexpected error encountered while attempting to create PowerHA SystemMirror service IP label: %s\n" $SERVICE_LABEL
            InternalErrorAbort
        }
    fi  # otherwise the service IP label is already defined

    return 0
}

#----------------------------------------------------------------------------
# Function:
#   getServiceNetwork
#
# Purpose:
#   Determine the appropriate network to place the service IP label
#   on based on adapter count per network per node
#
# Arguments:
#   (1) by reference - list of nodes to find interfaces for
#
# Output:
#   network name to place service IP label on
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function getServiceNetwork {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset -n NODES=$1
    typeset NETWORKS=$(clmgr query network | sort -u)
    typeset validNetworks
    typeset -A netXnodeCount
    typeset -A networkCount
    
    for network in $NETWORKS; do
        alias=$(clmgr query network $network |
        awk -F= '$1 ~ /ALIAS/ { print $2 }' | sed -e "s/\"//g")
        [[ "$alias" == "aliased" ]] && {
            validNetworks="$network $validNetworks"
        }
    done

    INTERFACES=$(clmgr query interface | sort -u)
    for interface in $INTERFACES; do
        node=$(clmgr query interface $interface |
            awk -F= '$1 ~ /NODE/ {print $2 }' | sed -e "s/\"//g")
        net=$(clmgr query interface $interface |
            awk -F= '$1 ~ /NETWORK/ {print $2 }' | sed -e "s/\"//g")
        [[ -n $node && -n $net ]] && {
            typeset -i count=${netXnodeCount[${net}_${node}]}
            (( count++ ))
            netXnodeCount[${net}_${node}]=$count
        }
    done

    typeset -i invalid=0
    for network in $validNetworks; do
        invalid=0
        for node in $NODES; do
            (( ${netXnodeCount[${net}_${node}]} == 0 )) && {
                invalid=1
            }
        done
        (( $invalid == 0 )) && {
            echo $network
            return 0
        }
    done
    return 1
}


#----------------------------------------------------------------------------
# Function:
#   generateVerifyScript
#
# Purpose:
#   Generates the cluster verification parameterized script for
#   existence of the SAP admin user (<SID>adm>), then pushes the file across to 
#   other nodes in the cluster
#
# Arguments:
#   (1) Component Identifier
#   (2) Application Name
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function generateVerifyScript {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset cid=$1
    typeset sa_id=$2
    typeset -n nodes=$3
    typeset localnode=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)

    typeset TEST_ROOT=/usr/es/sbin/cluster/etc/config/verify
    typeset VERIFICATION_FILENAME=${cid}".ver"

    [[ -z $sa_id || -z $cid ]] && return 1
    [[ -z $nodes ]] && return 1

    {
        getVerifyHeader $cid $sa_id
        getVerifySAPAdminUID_Test
        getVerifySAPAdminGID_Test
    } > $TEST_ROOT/$VERIFICATION_FILENAME

    for node in $nodes; do
        [[ "$node" != "$localnode" ]] && {
            cl_rcp $TEST_ROOT/$VERIFICATION_FILENAME \
                $node:$TEST_ROOT/$VERIFICATION_FILENAME
        }
    done

    typeset files=$(clmgr query file_collection SAPNW 2>/dev/null |
            grep -w FILE | awk -F= '{ print $2 }')
    
    clmgr -f delete file_collection SAPNW 2>/dev/null
    clmgr add file_collection SAPNW \
        FILES="$files $TEST_ROOT/$VERIFICATION_FILENAME" \
        ISPROPOGATEDFILEDURINGSYNC="true" 
        ISPROPOGATEAUTOWHENDETECTED="true" 2>/dev/null
    return 0
}
#----------------------------------------------------------------------------
# Function:
#   generateVerifyScript_ERS
#
# Purpose:
#   Generates the cluster verification parameterized script for
#   existence of the Enqueue replication server(enrepserver) file, 
#   then pushes the file across to other nodes in the cluster
#
# Arguments:
#   (1) Component Identifier
#   (2) Application Name
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function generateVerifyScript_ERS {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset cid=$1
    typeset sa_id=$2
    typeset -n nodes=$3
    typeset instances
    typeset localnode=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
    
    instances=$(echo $INSTANCE | awk -F "_" '{ for (i = 1; i <= NF; i++) printf("%s ", $i);}' 2>/dev/null)

    typeset TEST_ROOT=/usr/es/sbin/cluster/etc/config/verify
    typeset VERIFICATION_FILENAME=${sa_id}"_"${cid}".ver"

    [[ -z $sa_id || -z $cid ]] && return 1
    [[ -z $nodes ]] && return 1

    {
        getVerifyHeader $cid $sa_id
        for count in "${!instances[@]}"; do
            getVerifyENREPServerFile_Test ${instances[$count]}
        done
    } > $TEST_ROOT/$VERIFICATION_FILENAME

    for node in $nodes; do
        [[ "$node" != "$localnode" ]] && {
            cl_rcp $TEST_ROOT/$VERIFICATION_FILENAME \
                $node:$TEST_ROOT/$VERIFICATION_FILENAME
        }
    done

    typeset files=$(clmgr query file_collection SAPNW |
            grep FILES | awk -F= '{ print $2 }')
    
    clmgr -f delete file_collection SAPNW 2>/dev/null
    clmgr add file_collection SAPNW \
        FILES="$files $TEST_ROOT/$VERIFICATION_FILENAME" \
        ISPROPOGATEDFILEDURINGSYNC="true" 
        ISPROPOGATEAUTOWHENDETECTED="true" 2>/dev/null
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   getVerifyHeader
#
# Purpose:
#   Generate the verification parameterized script header
#   This should be called after setting up SAP Global Env.
#
# Arguments:
#   (1) Component ID
#   (2) Application Name
#
# Output:
#   Script output to stdout
#
# Returns:
#   n/a
#----------------------------------------------------------------------------

function getVerifyHeader {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset cid=$1
    typeset sa_id=$2

    typeset -A VerifyMsgs
    VerifyMsgs=(
        [ID_SAPNW_SAPGFS]="1"
        [NAME_SAPNW_SAPGFS]="SAP NW GFS"
        [ID_SAPNW_ERSINSTANCE]="2"
        [NAME_SAPNW_ERSINSTANCE]="SAP NW ERSINSTANCE"
        
    )

    echo "#\n# HACMP / SAP NW"
    echo "# Application Verificiation script generated for: $sa_id"
    echo "# Date: $(date)\n#\n"

    print -n "Component.Name.DefaultName = \""
    print -n ${VerifyMsgs[NAME_${sa_id}]}
    echo "\""

    echo "Component.Nodes = \"S=SAPNW:A=$sa_id\""
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   getVerifySAPAdminUID_Test
#
# Purpose:
#   Prints a script that will validate the SAP Admin user(<SID>adm) has the same
#   UID on all participating nodes in the cluster, uses the local UID
#   to validate the user. This should be called after setting up SAP Global Env.
#
# Arguments:
#   n/a
#
# Returns:
#   n/a
#----------------------------------------------------------------------------

function getVerifySAPAdminUID_Test {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    
    # Generates a test script that will:
    #
    # Obtain the SAP Admin UID, validate that the (<SID>adm>) user exists
    # on all nodes in the cluster with the same UID

    echo "\n#\n# Perform validation for user: $SAPADMNUSR\n#"

    echo "HAVerify.User.severity = \"ERROR\""
    echo "HAVerify.User.exists[0].name=\"$SAPADMNUSR\""

    uid=$(/usr/sbin/lsuser -a id $SAPADMNUSR | awk -F= '{ print $2 }')

    echo "HAVerify.User.exists[0].UID=$uid"
    return 0
}
#----------------------------------------------------------------------------
# Function:
#   getVerifySAPAdminGID_Test
#
# Purpose:
#   Prints a script that will validate the SAP group sapsys has the same
#   GID on all nodes that participate in the current application
#
# Arguments:
#   n/a
#
# Returns:
#   n/a
#----------------------------------------------------------------------------

function getVerifySAPAdminGID_Test {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    # Generates a test script that will:
    #
    # Test on all nodes the SAP group 'sapsys' exists on
    # all participating nodes of the application

    echo "\n#\n# Perform validation for group: sapsys\n#"

    echo "HAVerify.Group.severity = \"ERROR\""
    echo "HAVerify.Group.exists[0].name=\"sapsys\""

    gid=$(/usr/sbin/lsgroup -a id sapsys | awk -F= '{ print $2 }')

    echo "HAVerify.Group.exists[0].GID=$gid"
    return 0
}


#----------------------------------------------------------------------------
# Function:
#   getVerifyENREPServerFile_Test
#
# Purpose:
#   Prints a script that will validate the whether Enqueue replication server
#   file exists on all nodes. 
#   This should be called after setting up SAP Global Env.
#
# Arguments:
#   n/a
#
# Returns:
#   n/a
#----------------------------------------------------------------------------

function getVerifyENREPServerFile_Test {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset instance_name=$1
    # Generates a test script that will:
    #
    # Check if enrepserver file exists

    echo "\n#\n# Perform validation for file: /usr/sap/$SAPSYSTEMNAME/$instance_name/exe/enrepserver\n#"
    echo "HAVerify.File.severity = \"ERROR\""
    echo "HAVerify.File.exists[0].name=\"/usr/sap/$SAPSYSTEMNAME/$instance_name/exe/enrepserver\""
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   isVGAlreadyDefined
#
# Purpose:
#   Checks to ensure the volume group passed in is not already defined to
#   HACMP
#
# Arguments:
#   (1) Volume Group Name
#
# Returns:
#   0 volume group IS defined to HACMP
#   1 volume group is NOT defined to HACMP
#----------------------------------------------------------------------------

function isVolumeGroupAlreadyDefined {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset defVG=$1
    typeset vgs vg rg

    for rg in $(clmgr query resource_group); do
        vgs=$(clmgr query resource_group $rg | grep VOLUME_GROUP | awk -F'=' '{ print$2 }')
        vgs=${vgs//\"/}
        for vg in $vgs; do
            [[ "$vg" == "$defVG" ]] && {
                return 0
            }
        done

        vgs=$(clmgr query resource_group $rg | grep \
              CONCURRENT_VOLUME_GROUP | awk -F'=' '{ print $2 }')
        vgs=${vgs//\"/}
        for vg in $vgs; do
            [[ "$vg" == "$defVG" ]] && {
                return 0
            }
        done
    done
    return 1
}

#----------------------------------------------------------------------------
# Function:
#   isServiceIPLabelAlreadyDefined
#
# Purpose:
#   Validate that the service IP label isn't already defined in the HACMP
#   cluster.  If it is already defined, report an error and exit this script
#
# Arguments:
#   (1) Service IP Label
#
# Return:
#   1 if service IP label is not defined
#   exits on failure
#----------------------------------------------------------------------------

function isServiceIPLabelAlreadyDefined {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset serviceIP=$1
    for rg in $(clmgr query resource_group); do
        ips=$(clmgr query resource_group $rg | grep \
              SERVICE_LABEL | awk -F= '{ print $2 }')
        ips=${ips//\"/}
        for ip in $ips; do
            [[ "$ip" == "$serviceIP" ]] && {
                # add new messages here
                #user_msg 30 8 $serviceIP $rg
                #exit 1
                #Returning with value 1 here,
                #because the calling function will then group the calling instance with the RG where the VG is already defined.
                return 1
            }
        done
    done
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   isVGsAlreadyDefined
#
# Purpose:
#   Determine if a list of volume groups are already defined.  If a VG
#   is already define to HACMP, then report an error and abort
#
# Arguments:
#   (1) by ref List of HACMP volume groups
#
# Return:
#   0 on success
#   no return if failure (exit)
#----------------------------------------------------------------------------

function isVGsAlreadyDefined {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset -n vgs=$1
    typeset vg
    for vg in $vgs; do
        isVolumeGroupAlreadyDefined $vg
        (( $? != 1 )) && {
	    # add new messages here
            #user_msg 30 7 $vg
            #exit 1
            #Returning with value 1 here,
            #because the calling function will then group the calling instance with the RG where the VG is already defined.
            return 1
        }
    done
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   getUnusedName
#
# Purpose:
#   Obtain an un-used name for an HACMP component (application, monitor,
#   resource group, etc)
#
# Arguments:
#   (1) by reference - name 
#   (2) type - (as used in clmgr command 
#           resource_group | 
#           application | 
#           application_monitor, etc.)
#
# Output:
#   stdout contains the available name
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function getUnusedName {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset name=$1
    typeset type=$2
    typeset newname=$name
    typeset result
    typeset -i count=1

    result=$(clmgr query $type $newname 2>/dev/null)
    if [[ -n $result ]]; then
        while [[ -n $result ]]; do

            (( count++ ))

            # Give up after 9 attempts
            if (( $count > 9 )); then
                echo $name
                return 1
            fi
            newname=${name:0:31}
            newname=${newname}${count}
            result=$(clmgr query $type $newname 2>/dev/null)
        done
    fi
    echo $newname
}


#----------------------------------------------------------------------------
# Function:
#   validateAppName
#
# Purpose:
#   Validate the application name and ensure it contains only
#   valid characters
#
# Arguments:
#   (1) - Application Name
#
# Returns:
#   0 on valid name
#   1 name is invalid
#----------------------------------------------------------------------------

function validateAppName {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset appname=$1
    typeset -i invalid=0

    [[ -n ${appname//[a-zA-Z0-9_]/} ]] && {
        KLIB_SAP_SA_logmsg ERROR 30 10 sapsa.cat "Invalid application name: %s.\n\
            Valid PowerHA SystemMirror names must be at least one character long and can contain \
            characters ([A-Z, a-z]), numbers ([0-9]) and '_' (underscore). A name cannot begin with a number and a PowerHA SystemMirror reserved word cannot be a valid name.\n"
        return 1
    }
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   validateNodeLists
#
# Purpose:
#   Ensure the node lists contain nodes that are unique, primary
#   and takeover nodes should not have duplicates between the two
#   lists.
#
# Arguments:
#   (1) by reference - primary node
#   (2) by reference - takeover node list
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function validateNodeLists {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset -n primary=$1
    typeset -n takeover=$2

    typeset -A nodes
    nodes[$primary]=$primary
    for node in $takeover; do
        [[ -n ${nodes[$node]} ]] && {
             KLIB_SAP_SA_logmsg ERROR 30 9 sapsa.cat "ERROR: Node %s was used more than once in the takeover or\
                  primary node lists.  Please only use a node once in either the primary or takeover node lists.\n"
            return 1
        }
    done
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   checkAndSetPrimaryNode
#
# Purpose:
#   Reads the PrimaryNode information from the CONFIG_FILE, validates and sets it.
#
# Arguments:
#   1. tagID : Tag ID from where PrimaryNode node info need to be read from.
#   2. primary_node : This variable will be set wth the value of PrimaryNode read 
#      from the CONFIG_FILE
# Returns:
#   none
#--------------------------------------------------------------------------

function checkAndSetPrimaryNode {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset tagID=$1
    typeset -n primary_node=$2

    primary_node=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t $tagID | grep PrimaryNode)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.PrimaryNode" "checkAndSetPrimaryNode"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }
    [[ -z $primary_node ]] && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.PrimaryNode" "checkAndSetPrimaryNode"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }

    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 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 3 sapsa.cat "Primary Node \"%1\$s\" is not valid in the cluster.\n" $primary_node
        InternalErrorAbort
    }
}

#----------------------------------------------------------------------------
# Function:
#   checkAndSetTakeoverNodes
#
# Purpose:
#   Reads the PrimaryNode information from the CONFIG_FILE, validates and sets it.
#
# Arguments:
#   1. tagID : Tag ID from where PrimaryNode node info need to be read from.
#   2. primary_node : This variable will be set wth the value of PrimaryNode read
#      from the CONFIG_FILE
# Returns:
#   none
#--------------------------------------------------------------------------

function checkAndSetTakeoverNodes {
    typeset tagID=$1
    typeset -n takover_nodes=$2
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    takover_nodes=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t $tagID | grep TakeoverNodes)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.TakeoverNodes" "checkAndSetTakeoverNodes"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }
    [[ -z $takover_nodes ]] && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.TakeoverNodes" "checkAndSetTakeoverNodes"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }


    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
                break
            }
        done
        (( $flag == 0 )) && {
            found=0
             break
        }
    done

    (( $found == 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 4 sapsa.cat "One of the Takeover node from \"%1\$s\" is not valid in the cluster.\n" $takover_nodes
        InternalErrorAbort
    }
}

#----------------------------------------------------------------------------
# Function:
#   checkAndSetParticipatingNodes
#
# Purpose:
#   Reads the ParticipatingNodes information from the CONFIG_FILE, validates and sets it.
#
# Arguments:
#   1. tagID : Tag ID from where ParticipatingNodes node info need to be read from.
#   2. participating_nodes : This variable will be set wth the value of ParticipatingNodes read
#      from the CONFIG_FILE
# Returns:
#   none
#--------------------------------------------------------------------------

function checkAndSetParticipatingNodes {
    typeset tagID=$1
    typeset -n participating_nodes=$2
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    participating_nodes=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t $tagID | grep ParticipatingNodes)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.ParticipatingNodes" "checkAndSetParticipatingNodes"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }
    [[ -z $participating_nodes ]] && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.ParticipatingNodes" "checkAndSetParticipatingNodes"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }


    participating_nodes=$(echo $participating_nodes | cut -d"=" -f2)
    participating_nodes=$(echo $participating_nodes  | tr ',' ' ')
    found=1
    for pnode in $participating_nodes
    do
        flag=0
        for node in $(/usr/es/sbin/cluster/utilities/clnodename)
        do
            [[ $node == $pnode ]] && {
                flag=1
                break
            }
        done
        (( $flag == 0 )) && {
            found=0
            break
        }
    done

    (( $found == 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 4 sapsa.cat "One of the Participating nodes from \"%1\$s\" is not valid in the cluster.\n" $participating_nodes
        InternalErrorAbort
    }
}

#----------------------------------------------------------------------------
# Function:
#   importConfigFromFile
#
# Purpose:
#   Add a SAP Application to PowerHA From the inputs supplied in the XML file.
#
# Arguments:
#   n/a
#
# Returns:
#   0 on success
#   1 on failure
#--------------------------------------------------------------------------

function importConfigFromFile {
    typeset ascs_inst_name ascs_inst_num  ascs_pri_node ascs_take_node ascs_dbrg
    typeset ascs_service_ip ascs_service_ip_prefix ascs_vg ascs_service_network

    typeset scs_inst_name scs_inst_num  scs_pri_node scs_take_node scs_dbrg
    typeset scs_service_ip scs_service_ip_prefix scs_vg scs_service_network

    typeset ascs_ers_inst_name ascs_ers_inst_num  ascs_ers_participating_nodes
    typeset ascs_ers_service_ip ascs_ers_service_ip_prefix ascs_ers_vg ascs_ers_service_network

    typeset scs_ers_inst_name scs_ers_inst_num  scs_ers_participating_nodes
    typeset scs_ers_service_ip scs_ers_service_ip_prefix scs_ers_vg scs_ers_service_network


    typeset as_inst_name as_inst_num  as_pri_node as_take_node as_dbrg
    typeset as_service_ip as_service_ip_prefix as_vg as_service_network


    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    sap_id=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t SAP_SYSTEM_ID)
    (( $? != 0 )) && {
         KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_SYSTEM_ID" "importConfigFromFile"
         KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n" 
         InternalErrorAbort
    }
    sap_id=$(echo $sap_id | cut -d"=" -f2)
    SAPSYSTEMNAME=$sap_id
    SAPSID=$sap_id
    #Setup the SAP Global Variables for the above SID
    setSAPGlobalEnv $SAPSID
    configure_gfs=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t SAP_Global_FileSystem -a configure)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.configure" "importConfigFromFile"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }
    [[ -n $SAPSYSTEMNAME && $configure_gfs == "yes" ]] && {
        primeNode=""
        checkAndSetPrimaryNode "SAP_Global_FileSystem" primeNode
        PRINODE=$primeNode
        takeOverNodes=""
        checkAndSetTakeoverNodes "SAP_Global_FileSystem" takeOverNodes
        TAKENODE=$takeOverNodes
        base_path=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t SAP_Global_FileSystem | grep BASE_DIRECTORY_PATH)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.BASE_DIRECTORY_PATH" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }

        base_path=$(echo $base_path | cut -d"=" -f2)
        [[ -d $base_path ]] || {
             KLIB_SAP_SA_logmsg ERROR 90 5 sapsa.cat "Supplied directory \"%1\$s\" for BASE_DIRECTORY_PATH does not exist.\n" $base_path
            InternalErrorAbort
        }
        base_path=$(echo $base_path | sed "s/\/$//g")
        BASE_VG=""
        KLIB_AIX_add_vg_by_path BASE_VG $base_path "$BASE_VG"
        trans_path=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t SAP_Global_FileSystem | grep TRANS_DIRECTORY_PATH)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.TRANS_DIRECTORY_PATH" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }

        trans_path=$(echo $trans_path | cut -d"=" -f2)
        [[ -d $trans_path ]] || {
            KLIB_SAP_SA_logmsg ERROR 90 6 sapsa.cat "Supplied directory \"%1\$s\" for TRANS_DIRECTORY_PATH does not exist.\n" $trans_path
            InternalErrorAbort
        }
        #Remove extra / at the end
        trans_path=$(echo $trans_path | sed "s/\/$//g")
        TRANS_VG=""
        KLIB_AIX_add_vg_by_path TRANS_VG $trans_path "$TRANS_VG"
        [[ $BASE_VG != $TRANS_VG ]] && {
            VOLUME_GROUPS="$BASE_VG $TRANS_VG"
        } || {
            VOLUME_GROUPS="$BASE_VG"
        }
        #Removing leading and trailing spaces from VOLUME_GROUPS
        VOLUME_GROUPS=${VOLUME_GROUPS#+([[:space:]])}
        VOLUME_GROUPS=${VOLUME_GROUPS%+([[:space:]])}
        EXPORT_DIR="$base_path $trans_path"
        MOUNT_DIR1=$(echo "$SAPMNTDIR;$base_path" | tr -s " ")
        MOUNT_DIR2=$(echo "$SAPTRANSDIR;$trans_path" | tr -s " ")
        MOUNT_DIR="$MOUNT_DIR1 $MOUNT_DIR2"
        ipaddr=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t SAP_Global_FileSystem | grep IPAddress_or_name)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.IPAddress_or_name" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        SERVICE_LABEL=$(echo $ipaddr | cut -d"=" -f2)

        netmask=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t SAP_Global_FileSystem | grep Prefix_or_Netmask)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SAP_Global_FileSystem\.Prefix_or_Netmask" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        SERVICE_IP_LABEL_PREFIX=$(echo $netmask | cut -d"=" -f2)
        addSAPGFS   
    }

    configure_ascs=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance -a configure)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function %2$s\n" "ABAP_SCS_Instance\.configure" "importConfigFromFile"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }
    configure_scs=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance -a configure)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.configure" "importConfigFromFile"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }

    #Configure SCS Instance(s)
    [[ -n $SAPSYSTEMNAME && $configure_ascs == "yes" || $configure_scs == "yes" ]] && {
        [[ $configure_ascs == "yes" ]] && {
            ascs_inst_name=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep INSTANCE_NAME)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.INSTANCE_NAME" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            } 
            [[ -z $ascs_inst_name ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 9 sapsa.cat "ASCS instance name can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_inst_name=$(echo $ascs_inst_name | cut -d"=" -f2)
            ascs_inst_num=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep INSTANCE_NUMBER)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.INSTANCE_NUMBER" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ascs_inst_num ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 10 sapsa.cat "ASCS instance number can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_inst_num=$(echo $ascs_inst_num | cut -d"=" -f2)
            ascs_pri_node=""
            checkAndSetPrimaryNode "ABAP_SCS_Instance" ascs_pri_node
            ascs_take_node=""
            checkAndSetTakeoverNodes "ABAP_SCS_Instance" ascs_take_node
            ipaddr=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep IPAddress_or_name)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.IPAddress_or_name" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ipaddr ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 11 sapsa.cat "ASCS instance service IP can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            ascs_service_ip=$(echo $ipaddr | cut -d"=" -f2)
    
            netmask=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep Prefix_or_Netmask)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.Prefix_or_Netmask" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            ascs_service_ip_prefix=$(echo $netmask | cut -d"=" -f2)

            inst_dir=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep INSTANCE_DIRECTORY)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.INSTANCE_DIRECTORY" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $inst_dir ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 12 sapsa.cat "ASCS instance profile directory can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
    
            ascs_inst_dir=$(echo $inst_dir | cut -d"=" -f2)
            [[ -d $ascs_inst_dir ]] || {
                 KLIB_SAP_SA_logmsg ERROR 90 7 sapsa.cat "Supplied directory \"%1\$s\" for INSTANCE_DIRECTORY for ASCS Instance does not exist.\n" $ascs_inst_dir
                InternalErrorAbort
            }

            ascs_service_network=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep Service_Network)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.Service_Network" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ascs_service_network ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 35 sapsa.cat "ASCS Service Network can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_service_network=$(echo $ascs_service_network | cut -d"=" -f2)


            ascs_vg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep VOLUME_GROUP)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.VOLUME_GROUP" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ascs_vg ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 36 sapsa.cat "ASCS Volume Group can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_vg=$(echo $ascs_vg | cut -d"=" -f2)

            ascs_dbrg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_SCS_Instance | grep DBRG )
            (( $? != 0 )) && {
                 KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_SCS_Instance\.DBRG" "importConfigFromFile"
                 KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                 InternalErrorAbort
            }
	    ascs_dbrg=$(echo $ascs_dbrg | cut -d"=" -f2)

            if [[ -z $ascs_dbrg ]]
            then
                 ascs_dbrg="NONE";
            fi

            INSTANCE_NO=$ascs_inst_num
            INSTANCE=$ascs_inst_name
            VOLUME_GROUPS=$ascs_vg
            SERVICE_LABEL=$ascs_service_ip
            SERVICE_LABEL_PREFIX=$ascs_service_ip_prefix
            PRINODE=$ascs_pri_node
            TAKENODE=$ascs_take_node
            SERVICE_NETWORK=$ascs_service_network
            DBRG=$ascs_dbrg
            APPLICATION_ID=$(echo "SAP_"$SAPSYSTEMNAME"_"$INSTANCE)
            addSAPSCSInstance  
        }

        [[ $configure_scs == "yes" ]] && {
            scs_inst_name=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep INSTANCE_NAME)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.INSTANCE_NAME" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            } 
            [[ -z $scs_inst_name ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 13 sapsa.cat "SCS instance name can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_inst_name=$(echo $scs_inst_name | cut -d"=" -f2)
            scs_inst_num=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep INSTANCE_NUMBER)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.INSTANCE_NUMBER" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $scs_inst_num ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 14 sapsa.cat "SCS instance number can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_inst_num=$(echo $scs_inst_num | cut -d"=" -f2)
            scs_pri_node=""
            checkAndSetPrimaryNode "Java_SCS_Instance" scs_pri_node
            scs_take_node=""
            checkAndSetTakeoverNodes "Java_SCS_Instance" scs_take_node

            ipaddr=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep IPAddress_or_name)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.IPAddress_or_name" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ipaddr ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 15 sapsa.cat "SCS instance service IP can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            scs_service_ip=$(echo $ipaddr | cut -d"=" -f2)
    
            netmask=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep Prefix_or_Netmask)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.Prefix_or_Netmask" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            scs_service_ip_prefix=$(echo $netmask | cut -d"=" -f2)

            inst_dir=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep INSTANCE_DIRECTORY)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.INSTANCE_DIRECTORY" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $inst_dir ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "SCS instance profile directory can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

    
            scs_inst_dir=$(echo $inst_dir | cut -d"=" -f2)
            [[ -d $scs_inst_dir ]] || {
                KLIB_SAP_SA_logmsg ERROR 90 8 sapsa.cat "Supplied directory \"%1\$s\" for INSTANCE_DIRECTORY for SCS Instance does not exist.\n" $scs_inst_dir
                InternalErrorAbort
            }

            scs_service_network=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep Service_Network)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.Service_Network" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $scs_service_network ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 37 sapsa.cat "SCS Service Network can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_service_network=$(echo $scs_service_network | cut -d"=" -f2)

            scs_vg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep VOLUME_GROUP)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.VOLUME_GROUP" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $scs_vg ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 38 sapsa.cat "SCS Volume Group can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_vg=$(echo $scs_vg | cut -d"=" -f2)

            scs_dbrg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_SCS_Instance | grep DBRG )
           (( $? != 0 )) && {
                 KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_SCS_Instance\.DBRG" "importConfigFromFile"
                 KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                 InternalErrorAbort
            }
            scs_dbrg=$(echo $scs_dbrg | cut -d"=" -f2)

            if [[ -z $scs_dbrg ]]
            then
                 scs_dbrg="NONE";
            fi

            INSTANCE_NO=$scs_inst_num
            INSTANCE=$scs_inst_name
            VOLUME_GROUPS=$scs_vg
            SERVICE_LABEL=$scs_service_ip
            SERVICE_LABEL_PREFIX=$scs_service_ip_prefix
            PRINODE=$scs_pri_node
            TAKENODE=$scs_take_node
            SERVICE_NETWORK=$scs_service_network
            DBRG=$scs_dbrg
            APPLICATION_ID=$(echo "SAP_"$SAPSYSTEMNAME"_"$INSTANCE)
            addSAPSCSInstance 
        }

    }

    configure_ascs_ers=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance -a configure)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.configure" "importConfigFromFile"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }
    configure_scs_ers=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance -a configure)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_ERS_Instance\.configure" "importConfigFromFile"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }

    #Configure ERS Instance
    [[ -n $SAPSYSTEMNAME && $configure_ascs_ers == "yes" || $configure_scs_ers == "yes" ]] && {
        [[ $configure_ascs_ers == "yes" ]] && {
            ascs_ers_inst_name=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance | grep INSTANCE_NAME)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.INSTANCE_NAME" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            } 
            [[ -z $ascs_ers_inst_name ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 19 sapsa.cat "ASCS ERS instance name can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_ers_inst_name=$(echo $ascs_ers_inst_name | cut -d"=" -f2)
            ascs_ers_inst_num=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance | grep INSTANCE_NUMBER)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.INSTANCE_NUMBER" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ascs_ers_inst_num ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 20 sapsa.cat "ASCS ERS instance number can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_ers_inst_num=$(echo $ascs_ers_inst_num | cut -d"=" -f2)
            ascs_ers_participating_nodes=""
            checkAndSetParticipatingNodes "ABAP_ERS_Instance" ascs_ers_participating_nodes

            inst_dir=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance | grep INSTANCE_DIRECTORY)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.INSTANCE_DIRECTORY" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $inst_dir ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 22 sapsa.cat "ASCS ERS instance profile directory can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
    
            ascs_ers_inst_dir=$(echo $inst_dir | cut -d"=" -f2)
            [[ -d $ascs_ers_inst_dir ]] || {
                KLIB_SAP_SA_logmsg ERROR 90 29 sapsa.cat "Supplied directory \"%1\$s\" for INSTANCE_DIRECTORY for ASCS ERS Instance does not exist.\n" $ascs_ers_inst_dir
                InternalErrorAbort
            }

            ipaddr=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance | grep IPAddress_or_name)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.IPAddress_or_name" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ipaddr ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 15 sapsa.cat "ERS instance service IP can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            ascs_ers_service_ip=$(echo $ipaddr | cut -d"=" -f2)

            netmask=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance | grep Prefix_or_Netmask)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.Prefix_or_Netmask" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            ascs_ers_service_ip_prefix=$(echo $netmask | cut -d"=" -f2)


            ascs_ers_service_network=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance | grep Service_Network)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.Service_Network" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ascs_ers_service_network ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 39 sapsa.cat "ASCS ERS  Service Network can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_ers_service_network=$(echo $ascs_ers_service_network | cut -d"=" -f2)

            ascs_ers_vg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t ABAP_ERS_Instance | grep VOLUME_GROUP)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "ABAP_ERS_Instance\.VOLUME_GROUP" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ascs_ers_vg ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 40 sapsa.cat "ASCS ERS  Volume Group can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            ascs_ers_vg=$(echo $ascs_ers_vg | cut -d"=" -f2)

            INSTANCE_NO=$ascs_ers_inst_num
            INSTANCE=$ascs_ers_inst_name
            VOLUME_GROUPS=$ascs_ers_vg
            PARTICIPATING_NODES=$ascs_ers_participating_nodes
            SERVICE_LABEL=$ascs_ers_service_ip
            SERVICE_LABEL_PREFIX=$ascs_ers_service_ip_prefix
            SERVICE_NETWORK=$ascs_ers_service_network
            APPLICATION_ID=$(echo "SAP_"$SAPSYSTEMNAME"_"$INSTANCE)
              pcount=0
               for i in $PARTICIPATING_NODES
                do
                     participating_nodes[$pcount]=$i
                     ((pcount=$pcount+1))
                done

            addSAPERSInstance 
        }

        [[ $configure_scs_ers == "yes" ]] && {
            scs_ers_inst_name=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance | grep INSTANCE_NAME)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_ERS_Instance\.INSTANCE_NAME" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            } 
            [[ -z $scs_ers_inst_name ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 23 sapsa.cat "SCS ERS instance name can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_ers_inst_name=$(echo $scs_ers_inst_name | cut -d"=" -f2)
            scs_ers_inst_num=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance | grep INSTANCE_NUMBER)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_ERS_Instance\.INSTANCE_NUMBER" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $scs_ers_inst_num ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 14 sapsa.cat "SCS ERS instance number can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_ers_inst_num=$(echo $scs_ers_inst_num | cut -d"=" -f2)
            scs_ers_participating_nodes=""
            checkAndSetParticipatingNodes "Java_ERS_Instance" scs_ers_participating_nodes

            inst_dir=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance | grep INSTANCE_DIRECTORY)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_ERS_Instance\.INSTANCE_DIRECTORY" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $inst_dir ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 26 sapsa.cat "SCS ERS instance profile directory can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            scs_ers_inst_dir=$(echo $inst_dir | cut -d"=" -f2)
            [[ -d $scs_ers_inst_dir ]] || {
                KLIB_SAP_SA_logmsg ERROR 90 30 sapsa.cat "Supplied directory \"%1\$s\" for INSTANCE_DIRECTORY for SCS ERS Instance does not exist.\n" $scs_ers_inst_dir
                InternalErrorAbort
            }

            ipaddr=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance | grep IPAddress_or_name)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_ERS_Instance\.IPAddress_or_name" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $ipaddr ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 15 sapsa.cat "ERS instance service IP can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            scs_ers_service_ip=$(echo $ipaddr | cut -d"=" -f2)

            netmask=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance | grep Prefix_or_Netmask)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "Java_ERS_Instance\.Prefix_or_Netmask" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }

            scs_ers_service_ip_prefix=$(echo $netmask | cut -d"=" -f2)

            scs_ers_service_network=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance | grep Service_Network)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "JAVA_ERS_Instance\.Service_Network" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $scs_ers_service_network ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 41 sapsa.cat "SCS ERS  Service Network can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_ers_service_network=$(echo $scs_ers_service_network | cut -d"=" -f2)

            scs_ers_vg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t Java_ERS_Instance | grep VOLUME_GROUP)
            (( $? != 0 )) && {
                KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "JAVA_ERS_Instance\.VOLUME_GROUP" "importConfigFromFile"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            [[ -z $scs_ers_vg ]] && {
                KLIB_SAP_SA_logmsg ERROR 90 42 sapsa.cat "SCS ERS Volume Group can't be null in the supplied XML File"
                KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
                InternalErrorAbort
            }
            scs_ers_vg=$(echo $scs_ers_vg | cut -d"=" -f2)

            INSTANCE_NO=$scs_ers_inst_num
            INSTANCE=$scs_ers_inst_name
            VOLUME_GROUPS=$scs_ers_vg
            PARTICIPATING_NODES=$scs_ers_participating_nodes
            SERVICE_LABEL=$scs_ers_service_ip
            SERVICE_LABEL_PREFIX=$scs_ers_service_ip_prefix
            SERVICE_NETWORK=$scs_ers_service_network
            APPLICATION_ID=$(echo "SAP_"$SAPSYSTEMNAME"_"$INSTANCE)
                pcount=0
               for i in $PARTICIPATING_NODES
                do
                    participating_nodes[$pcount]=$i
                    ((pcount=$pcount+1))
                done

            addSAPERSInstance 
        }

 
    }
    #Configure AS/Dialog Instance
    configure_as=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance -a configure)
    (( $? != 0 )) && {
        KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.configure" "importConfigFromFile"
        KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
        InternalErrorAbort
    }

    [[ $configure_as == "yes" ]] && {
        as_inst_name=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep INSTANCE_NAME)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.INSTANCE_NAME" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        } 
        [[ -z $as_inst_name ]] && {
            KLIB_SAP_SA_logmsg ERROR 90 31 sapsa.cat "AS instance name can't be null in the supplied XML File"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        as_inst_name=$(echo $as_inst_name | cut -d"=" -f2)
        as_inst_num=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep INSTANCE_NUMBER)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.INSTANCE_NUMBER" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        [[ -z $as_inst_num ]] && {
            KLIB_SAP_SA_logmsg ERROR  90 32 sapsa.cat "AS instance number can't be null in the supplied XML File"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        as_inst_num=$(echo $as_inst_num | cut -d"=" -f2)
        as_pri_node=""
        checkAndSetPrimaryNode "AS_Instance" as_pri_node
        as_take_node=""
        checkAndSetTakeoverNodes "AS_Instance" as_take_node
        ipaddr=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep IPAddress_or_name)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.IPAddress_or_name" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        [[ -z $ipaddr ]] && {
            KLIB_SAP_SA_logmsg ERROR 90 33 sapsa.cat "AS instance service IP can't be null in the supplied XML File"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }

        as_service_ip=$(echo $ipaddr | cut -d"=" -f2)

        netmask=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep Prefix_or_Netmask)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.Prefix_or_Netmask" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }

        as_service_ip_prefix=$(echo $netmask | cut -d"=" -f2)

        inst_dir=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep INSTANCE_DIRECTORY)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.INSTANCE_DIRECTORY" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        [[ -z $inst_dir ]] && {
            KLIB_SAP_SA_logmsg ERROR 90 34 sapsa.cat "AS instance profile directory can't be null in the supplied XML File"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }


        as_inst_dir=$(echo $inst_dir | cut -d"=" -f2)
        [[ -d $as_inst_dir ]] || {
            KLIB_SAP_SA_logmsg ERROR 120 16 sapsa.cat "Supplied directory \"%1\$s\" for INSTANCE_DIRECTORY for AS Instance does not exist.\n" $as_inst_dir
            InternalErrorAbort
        }

        as_service_network=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep Service_Network)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.Service_Network" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        [[ -z $as_service_network ]] && {
            KLIB_SAP_SA_logmsg ERROR 90 43 sapsa.cat "AS Service Network can't be null in the supplied XML File"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        as_service_network=$(echo $as_service_network | cut -d"=" -f2)

        as_vg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep VOLUME_GROUP)
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.VOLUME_GROUP" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        [[ -z $as_vg ]] && {
            KLIB_SAP_SA_logmsg ERROR 90 44 sapsa.cat "AS Volume Group can't be null in the supplied XML File"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        as_vg=$(echo $as_vg | cut -d"=" -f2)

        as_dbrg=$(clsaxmlutil -s -x $CONFIG_FILE -m $SAP_MANUAL_CONFIG_SCHEMA -t AS_Instance | grep DBRG )
        (( $? != 0 )) && {
            KLIB_SAP_SA_logmsg ERROR 90 2 sapsa.cat "Problem in parsing \"%1\$s\" tag in function \"%2\$s\" \n" "AS_Instance\.DBRG" "importConfigFromFile"
            KLIB_SAP_SA_logmsg ERROR 90 1 sapsa.cat "Problem with XML configuration file. Ensure a valid XML file supplied.\n"
            InternalErrorAbort
        }
        as_dbrg=$(echo $as_dbrg | cut -d"=" -f2)
        if [[ -z $as_dbrg ]]
        then
             as_dbrg="NONE";
        fi

        INSTANCE_NO=$as_inst_num
        INSTANCE=$as_inst_name
        VOLUME_GROUPS=$as_vg
        SERVICE_LABEL=$as_service_ip
        SERVICE_LABEL_PREFIX=$as_service_ip_prefix
        PRINODE=$as_pri_node
        TAKENODE=$as_take_node
        SERVICE_NETWORK=$as_service_network
        DBRG=$as_dbrg

        APPLICATION_ID=$(echo "SAP_"$SAPSYSTEMNAME"_"$INSTANCE)
        addSAPASInstance
    }

}

#----------------------------------------------------------------------------
# Main
#----------------------------------------------------------------------------

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

while getopts t:s:i:a:p:T:I:V:E:M:P:N:f:n:r: option
do
    case $option in 
        t)  # Type of instance
            TYPE=$OPTARG
        ;;
        s)  # SAPSYSTEMNAME
            SAPSID=$OPTARG
        ;;
        i)  # SAP Instance Name
            INSTANCE=$OPTARG
            # We need to grep Instance No from Instance name
            if [[ ! -z $INSTANCE ]]; then
                INSTANCE_NO=${INSTANCE##${INSTANCE%%??}}
            fi
        ;;
        a)  # Application ID
            APPLICATION_ID=$OPTARG
            APPLICATION_ID=${APPLICATION_ID// /}    # Remove whitespace
            validateAppName $APPLICATION_ID
            (( $? != 0 )) && exit 1
        ;;
        p)  # Primary node
            PRINODE=$OPTARG
        ;;
        T)  # Takeover node
            TAKEOVER_NODES=$OPTARG
            TAKEOVER_NODES_TOKENIZED=$(echo $TAKEOVER_NODES | sed -e "s/ /\:/g")
            TAKENODE=$(echo $TAKEOVER_NODES | sed -e "s/\:/ /g")
        ;;
        I)  # Service IP labels
            SERVICE_LABEL=$OPTARG
        ;;
        V)  # Shared Volume Groups
            VOLUME_GROUPS=$OPTARG
        ;;
        E)  #Export Directories (used with type=GFS)
            EXPORT_DIR=$OPTARG
        ;;
        M)  #Mount Directories (used with type=GFS)
            MOUNT_DIR=$OPTARG
        ;;
        P)  #Participating nodes (used with type=ERS)
            PARTICIPATING_NODES=$OPTARG 
        ;;
        N)  #Participating nodes (used with type=ERS)
            PARTICIPATING_NODES=$OPTARG 
        ;;
        n)  #Network Interface 
            SERVICE_NETWORK=$OPTARG 
        ;;
        r)  #DataBase Resource Group 
            DBRG=$OPTARG 
        ;;
        f)
            #Manual Configuration Mode
            MANUAL_CONFIG=true
            CONFIG_FILE=$OPTARG
            ;;
        *)
        ;;
    esac
done

if [[ -z $DBRG ]] 
then
     DBRG="NONE";
else
    typeset var
    var=$(/usr/es/sbin/cluster/utilities/cllsgrp | grep -w $DBRG)
    if [[ -z $var ]]
    then
	KLIB_SAP_SA_logmsg ERROR 40 18 sapsa.cat "ERROR: Specified DATABASE RG is not valid.\n"
	exit 0
    fi
fi

if [[ -z $PARTICIPATING_NODES ]]
then
    PARTICIPATING_NODES="$PRINODE $TAKENODE"
fi

# Eliminating duplicates in PARTICIPATING_NODES
PARTICIPATING_NODES=$(echo $PARTICIPATING_NODES | tr ' ' '\n' | sort -u | tr '\n' ' ')

for i in $PARTICIPATING_NODES
do
    participating_nodes[$pcount]=$i
    (( pcount++ ))
done

# 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

# No type specified, abort immediately
[[ -z $TYPE ]] && exit 1

#
# Ensure the node lists for primary and takeover
# do not contain duplicates (a single node used more than once)
#
if [[ -n $PRINODE && -n $TAKENODE ]]; then
    validateNodeLists PRINODE TAKENODE 
fi

typeset -A addInstanceMethod
addInstanceMethod=(
    [GFS]="addSAPGFS"
    [AS]="addSAPASInstance"
    [SCS]="addSAPSCSInstance"
    [ERS]="addSAPERSInstance"
)

if [[ -z ${addInstanceMethod[$TYPE]} ]]; then
    exit 1
fi

${addInstanceMethod[$TYPE]}
exit $?
