#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2019,2020,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
# 61haes_r721 src/43haes/usr/sbin/cluster/sa/sap/sbin/cl_instanceresources.sh 1.29 
#
# Licensed Materials - Property of IBM 
#  
# Restricted Materials of IBM 
#  
# COPYRIGHT International Business Machines Corp. 2008,2016 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG
#
# @(#)  7d4c34b 43haes/usr/sbin/cluster/sa/sap/sbin/cl_instanceresources.sh, 726, 2147A_aha726, Feb 05 2021 09:50 PM
# 
##
## NAME:    cl_instanceresources
##
## PURPOSE:
##          Produces the output suitable for parsing by SMIT screen's 
##          command to discovery.
##
##
## ARGUMENTS:
##
##  Type:
##      -t GFS/AS/SCS/ERS
##
##
## OUTPUT:
## 
## 
## RETURNS:
##      0 on success
##      1 on failure
##
. /usr/es/lib/ksh93/func_include
version='1.29'

#----------------------------------------------------------------------------
# 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)

#----------------------------------------------------------------------------
# Function:
#   trimToValue
#
# Purpose:
#   Trims the given string to value 
#
# Output:
#    value without quotes 
#
# Returns:
#   value
#----------------------------------------------------------------------------

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

    typeset input=$1
    input=${input/*=/}
    input=${input#" "}
    input=${input%" "}
    input=${input//\"/}

    echo "$input"
}

#----------------------------------------------------------------------------
# Function:
#   setAttributesValues
#
# Purpose:
#   Gets the complete list of attributes and values of perticulat applicaiton ID
#   and exports the values to same variable.
#
# Output:
#    export
#
# Returns:
#   None
#----------------------------------------------------------------------------

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

    typeset app_id=$1

    odmget -q "application_id=$app_id" HACMPsa_metadata | grep -e name -e value 2>/dev/null | while read line ; do 

        name=$( trimToValue "$line" )
        read line2
        value=$( trimToValue "$line2" )
        eval "pre_value=\${$name}"
        if [[ -n $pre_value ]]; then 
            export $name="$pre_value $value"
        else
            export $name="$value"
        fi
   done
}

#----------------------------------------------------------------------------
# Function:
#   checkGFSPropertiesGlobally
#
# Purpose:
#   To check across the cluster for SAP GFS properties.
#
# Output:
#   <SAP Global File System Owning Node>:<Takeover Nodes>:<Service IP Label>:
#    <Shared Volume Groups>:<Filesystems/Directories to Export (NFSv2/3)>:
#    <Filesystems/Directories to NFS Mount>
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function checkGFSPropertiesGlobally {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset ret
    typeset INSTANCE_NAME=$1
    #Before we go across the cluster, check locally.
    out=$(checkAndListGFSPropertiesLocally)
    ret=$?
    (( $ret != 0 )) && {
        typeset -A list
        typeset nodes localnode node
        KLIB_HACMP_list_nodes list
        nodes=${list[*]}
        localnode=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
        for node in $nodes; do
            [[ $node == $localnode ]] && continue 
            out=$(cl_rsh $node \
                  "/usr/es/sbin/cluster/sa/sap/sbin/cl_instanceresources -i $INSTANCE_NAME -L")
            ret=$?
            (( $ret == 0 )) && break
        done
    }
    echo "$out"
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   checkAndListGFSPropertiesLocally
#
# Purpose:
#   List the properties of the SAP Global Filesystem for SMIT screen's command 
#   to discovery if it is locally available.
#
# Output:
#   <SAP Global File System Owning Node>:<Takeover Nodes>:<Service IP Label>:
#    <Shared Volume Groups>:<Filesystems/Directories to Export (NFSv2/3)>:
#    <Filesystems/Directories to NFS Mount>
#
# Returns:
#   0 on success
#   1 on failure
#

function checkAndListGFSPropertiesLocally {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    if ! checkIsGFSLocallyAvailable
    then
	return 1
    fi
    listGFSProperties
}

#----------------------------------------------------------------------------
# Function:
#   checkIsGFSLocallyAvailable
#
# Purpose:
#   Checks if we have SAP Global filesystem locally available.
#
# Arguments:
#   None.
#
# Returns:
#   0 -> For yes
#   1 -> For No
#
function checkIsGFSLocallyAvailable {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset sapmntvg saptransvg sapmntdir transdir
    typeset -i out ret

    if ! setSAPGlobalEnv $SID
    then
	return 1
    fi

    # Check if RBAC is enabled
    typeset is_rbac_enabled=""
    is_rbac_enabled=$(/usr/es/sbin/cluster/utilities/clodmget -nq "group=LDAPClient and name=RBACConfig" -f value HACMPLDAP 2>/dev/null)

    # For a non root user, append the user name to the output file.
    [[ -z "$LOGIN" ]] && user_name=$(id -nu 2>/dev/null) || user_name="$LOGIN"
    if [[ $user_name != "root" && $is_rbac_enabled == "YES" ]];then
        CL_DATFILE="/var/hacmp/tmp/sa_config"_$user_name
    else
        CL_DATFILE="/var/hacmp/tmp/sa_config"
    fi

    typeset LOCALNODENAME=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
    out=$(grep "^${LOCALNODENAME}:" $CL_DATFILE | \
          grep -w "SAPNW_SAPGFS" | grep $SID | cut -d":" -f6)
    (( $out == 0 )) && return 1

    sapmntdir=$(mount | grep -w "$SAPMNTDIR" | awk '{print $2}')
    [[ -z $sapmntdir ]] && return 1
    saptransdir=$(mount | grep -w "$SAPMNTDIR" | awk '{print $2}')
    [[ -z $saptransdir ]] && return 1
    sapmntvg=$(KLIB_AIX_get_vg_by_path $sapmntdir)
    [[ -z $sapmntvg ]] && return 1
    saptransvg=$(KLIB_AIX_get_vg_by_path $saptransdir)
    [[ -z $saptransvg ]] && return 1
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   listGFSProperties
#
# Purpose:
#   List the properties of the SAP Global Filesystem for SMIT screen's command 
#   to discovery.
#
# Output:
#   <SAP Global File System Owning Node>:<Takeover Nodes>:<Service IP Label>:
#    <Shared Volume Groups>:<Filesystems/Directories to Export (NFSv2/3)>:
#    <Filesystems/Directories to NFS Mount>
#    This function is called from checkIsGFSLocallyAvailable
#
# Arguments:
#   None.
#
# Returns:
#   0 -> For yes
#   1 -> For No
#
function listGFSProperties {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x

    typeset appname=$(echo "SAP_"$SID"_GFS")
    typeset gfs_ip

    if ! setSAPGlobalEnv $SID
    then
	return 1
    fi

    typeset sapmntvg saptransvg shared_vg export_dir mount_dir allVGs
    typeset localnode 

    localnode=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
    sapmntdir=$(mount | grep " $SAPMNTDIR" | awk '{print $2}' 2>/dev/null)
    gfs_ip=$(mount | grep -w "$SAPMNTDIR" | awk '{print $1}' 2>/dev/null)
    saptransdir=$(mount | grep -w "$gfs_ip" | grep "$SAPTRANSDIR" | awk '{print $2}' 2>/dev/null)
    sapmntvg=$(KLIB_AIX_get_vg_by_path $sapmntdir)
    saptransvg=$(KLIB_AIX_get_vg_by_path $saptransdir)
    shared_vg=$(echo $sapmntvg $saptransvg)
    KLIB_UTIL_LIST_unique_key_list shared_vg $shared_vg
    export_dir="$sapmntdir $saptransdir"
    mount_dir=$(echo "$SAPMNTDIR;$sapmntdir $SAPTRANSDIR;$saptransdir")

    echo "#sapsystem:appname:primary:takeover:service_ip:shared_vg:export_dir:mount_dir"
    echo "$SID:$appname:$localnode:::$shared_vg:$export_dir:$mount_dir"
}


#----------------------------------------------------------------------------
# Function:
#   checkASPropertiesGlobally
#
# Purpose:
#   To check across the cluster for SAP GFS properties.
#
# Output:
#   <SID>:<SAP Application Instance Name>:<Instance no>:<Application Name>:
#   <Primary Node>:<Takeover Nodes>:<Service IP Label>:<Volume Groups>
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

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

    typeset ret
    typeset INSTANCE_NAME=$1
    #Before we go across the cluster, check locally.
    out=$(checkAndListASPropertiesLocally $INSTANCE_NAME)
    ret=$?
    (( $ret != 0 )) && {
        typeset -A list
        typeset nodes localnode node
        KLIB_HACMP_list_nodes list
        nodes=${list[*]}
        localnode=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
        for node in $nodes; do
            [[ "$node" == "$localnode" ]] && continue 
            out=$(cl_rsh $node \
                 "/usr/es/sbin/cluster/sa/sap/sbin/cl_instanceresources -i $INSTANCE_NAME -L")
            ret=$?
            (( $ret == 0 )) && break
        done
    }
    echo "$out"
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   checkAndListASPropertiesLocally
#
# Purpose:
#   To check locally for the given application instance properties
#
# Output:
#   <SID>:<SAP Application Instance Name>:<Instance no>:<Application Name>:
#   <Primary Node>:<Takeover Nodes>:<Service IP Label>:<Volume Groups>
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function checkAndListASPropertiesLocally {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset instance_name=$1
    typeset allASInstances
    setSAPGlobalEnv -i $instance_name
    ret=$?
    (( $ret != 0 )) && return 1
    getAllRunningASInstances allASInstances
    	# changed to isInTheList in other instances as a defect earlier.
        isInTheList allASInstances $instance_name && {
        listASProperties $instance_name
        return 0
    }
    return 1
}

#----------------------------------------------------------------------------
# Function:
#   listASProperties
#
# Purpose:
#   To check locally for the given application instance properties
#
# Output:
#   <SID>:<SAP Application Instance Name>:<Instance no>:<Application Name>:
#   <Primary Node>:<Takeover Nodes>:<Service IP Label>
#    This function is called only from checkAndListASPropertiesLocally
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function listASProperties {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset startProfiles
    typeset instance_name=$1
    typeset INSTANCE_NAME virt_ip instance_dir instance_no
    getAllSAPInstanceStartupProfiles startProfiles
    for dir in "${!startProfiles[@]}"; do
        INSTANCE_NAME=$(getInstanceNameFromProfile ${startProfiles[$dir]})
        [[ $INSTANCE_NAME == $instance_name ]] && {
            virt_ip=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  $SAPEXEDIR/sappfpar \
                      pf=${startProfiles[$dir]} SAPLOCALHOST" 2>/dev/null)
            
            instance_no=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  $SAPEXEDIR/sappfpar \
                      pf=${startProfiles[$dir]} SAPSYSTEM" 2>/dev/null)
            
            appname=$(echo "SAP_"$SAPSYSTEMNAME"_"$instance_name)
            local_node_name=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
            echo "#sapsystem:instance:instance_no:appname:primary:takeover:service_ip"
            echo "$SAPSYSTEMNAME:$instance_name:$instance_no:$appname:$local_node_name::$virt_ip"
            return 0
        }
    done
    echo "#sapsystem:instance:instance_no:appname:primary:takeover:service_ip:shared_vg"
    echo ":::::::"
}

#----------------------------------------------------------------------------
# Function:
#   checkSCSPropertiesGlobally
#
# Purpose:
#   To check across the cluster for SAP SCS instance properties
#
# Output:
#   <SID>:<SAP SCS/ASCS Instance(s) Name(s)>:<Instance No.>:<Application Name>:
#   <Primary Node>:<Takeover Nodes>:<Service IP Label>:<Volume Groups>
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function checkSCSPropertiesGlobally {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset ret
    typeset INSTANCE_NAME=$1
    #Before we go across the cluster, check locally.
    out=$(checkAndListSCSPropertiesLocally $INSTANCE_NAME)
    ret=$?
    (( $ret != 0 )) && {
        typeset -A list
        typeset nodes localnode node
        KLIB_HACMP_list_nodes list
        nodes=${list[*]}
        localnode=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
        for node in $nodes; do
            [[ "$node" == "$localnode" ]] && continue 
            out=$(cl_rsh $node \
                  "/usr/es/sbin/cluster/sa/sap/sbin/cl_instanceresources -i $INSTANCE_NAME -L")
            ret=$?
            (( $ret == 0 )) && break
        done
    }
    echo "$out"
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   checkAndListSCSPropertiesLocally
#
# Purpose:
#   To check locally for the given scs instance properties for SMIT screens
#
# Output:
#   <SID>:<SAP SCS/ASCS Instance(s) Name(s)>:<Instance No.>:<Application Name>:
#   <Primary Node>:<Takeover Nodes>:<Service IP Label>
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function checkAndListSCSPropertiesLocally {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset instance_name=$1 
    typeset instance_nos
    typeset allSCSInstances out
    setSAPGlobalEnv -i $instance_name
    ret=$?
    (( $ret != 0 )) && return 1
    getAllRunningSCSInstances allSCSInstances
    (( ${#allSCSInstances[*]} == 0 )) && return 1
    local_node_name=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
    instances=$( echo $instance_name | awk -F "_" \
               '{ for (i = 1; i <= NF; i++) printf("%s ", $i);}' 2>/dev/null )
    for count in "${!instances[@]}"; do
        isInTheList allSCSInstances ${instances[$count]} && {
            out=$(listSCSProperties ${instances[$count]})
            instance_nos[$count]=$(echo "$out" 2>/dev/null | \
                                   tail -n 1 | cut -d":" -f3 2>/dev/null)
            service_ips[$count]=$(echo "$out" 2>/dev/null | \
                                  tail -n 1 | cut -d":" -f7 2>/dev/null)
        }
    done
    instance_num=$(echo ${instance_nos[*]} | tr ' ' '_')
    KLIB_UTIL_LIST_unique_key_list shared_vgs ${shared_vgs[*]}
    KLIB_UTIL_LIST_unique_key_list service_ips ${service_ips[*]}
    	appname=$(echo "SAP_"$SAPSYSTEMNAME"_"$instance_name)
    echo "#sapsystem:instance:instance_no:appname:primary:takeover:service_ip"
    echo "$SAPSYSTEMNAME:$instance_name:$instance_num:$appname:$local_node_name::$service_ips"
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   listSCSProperties
#
# Purpose:
#   To check locally for the given scs instance properties for SMIT screens
#
# Output:
#   <SID>:<SAP SCS/ASCS Instance(s) Name(s)>:<Instance No.>:<Application Name>:
#   <Primary Node>:<Takeover Nodes>:<Service IP Label>:<Volume Groups>
#    This function is called only from checkAndListSCSPropertiesLocally
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function listSCSProperties {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset startProfiles
    typeset instance_name=$1
    typeset INSTANCE_NAME virt_ip instance_dir instance_no
    echo 
    getAllSAPInstanceStartupProfiles startProfiles
    for dir in "${!startProfiles[@]}"; do
        INSTANCE_NAME=$(getInstanceNameFromProfile ${startProfiles[$dir]})
        [[ $INSTANCE_NAME == $instance_name ]] && {
            virt_ip=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
                      $SAPEXEDIR/sappfpar pf=${startProfiles[$dir]} SAPLOCALHOST" 2>/dev/null)

            instance_no=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
                         $SAPEXEDIR/sappfpar pf=${startProfiles[$dir]} SAPSYSTEM" 2>/dev/null)

            instance_dir=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
                                $SAPEXEDIR/sapcontrol \
                                -nr $instance_no -host $virt_ip \
                                -function ParameterValue DIR_INSTANCE \
                                -format script" 2>/dev/null | \
                                tail -n 1 | awk -F":" '{print $2}' 2>/dev/null)

            shared_vg=$(KLIB_AIX_get_vg_by_path $instance_dir)
	    appname=$(echo "SAP_"$SAPSYSTEMNAME"_"$instance_name)
            local_node_name=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
            echo "#sapsystem:instance:instance_no:appname:primary:takeover:service_ip:shared_vg"
            echo "$SAPSYSTEMNAME:$instance_name:$instance_no:$appname:$local_node_name::$virt_ip:$shared_vg"
            return 0
        }
    done
    echo "#sapsystem:instance:instance_no:appname:primary:takeover:service_ip:shared_vg"
    echo ":::::::"
}

#----------------------------------------------------------------------------
# Function:
#   checkERSPropertiesGlobally
#
# Purpose:
#   To check across the cluster for SAP ERS instance properties
#
# Output:
#   <SID>:<SAP ERS Instance(s) Name(s)>:<Instance Nos.>:<Application Name>:
#    <Participating Nodes>
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function checkERSPropertiesGlobally {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset ret
    typeset INSTANCE_NAME=$1
    #Before we go across the cluster, check locally.
    out=$(checkAndListERSPropertiesLocally $INSTANCE_NAME)
    ret=$?
    (( $ret != 0 )) && {
        typeset -A list
        typeset nodes localnode node
        KLIB_HACMP_list_nodes list
        nodes=${list[*]}
        localnode=$(/usr/es/sbin/cluster/utilities/get_local_nodename 2>/dev/null)
        for node in $nodes; do
            [[ "$node" == "$localnode" ]] && continue 
            out=$(cl_rsh $node \
                  "/usr/es/sbin/cluster/sa/sap/sbin/cl_instanceresources -i $INSTANCE_NAME -L")
            ret=$?
            (( $ret == 0 )) && break
        done
    }
    echo "$out"
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   checkAndListERSPropertiesLocally
#
# Purpose:
#   To check locally for the given ERS instance properties for SMIT screens
#
# Output:
#   <SID>:<SAP ERS Instance(s) Name(s)>:<Instance Nos.>:<Application Name>:
#    <Participating Nodes>
#
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function checkAndListERSPropertiesLocally {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset instance_name=$1 
    typeset instance_nos
    typeset allERSInstances out
    setSAPGlobalEnv -i $instance_name
    ret=$?
    (( $ret != 0 )) && return 1
    getAllRunningERSInstances allERSInstances
    (( ${#allERSInstances[*]} == 0 )) && return 1
    instances=$( echo $instance_name | awk -F "_" \
               '{ for (i = 1; i <= NF; i++) printf("%s ", $i);}' 2>/dev/null )
    for count in "${!instances[@]}"; do
        isInTheList allERSInstances ${instances[$count]} && {
            out=$(listERSProperties ${instances[$count]})
            instance_nos[$count]=$(echo "$out" 2>/dev/null | \
                                   tail -n 1 | cut -d":" -f3 2>/dev/null)

            service_ips[$count]=$(echo "$out" 2>/dev/null | \
                                  tail -n 1 | cut -d":" -f5 2>/dev/null)

        }
    done
    instance_num=$(echo ${instance_nos[*]} | tr ' ' '\n')
    KLIB_UTIL_LIST_unique_key_list shared_vgs ${shared_vgs[*]}
    KLIB_UTIL_LIST_unique_key_list service_ips ${service_ips[*]}
    appname=$(echo "SAP_"$SAPSYSTEMNAME"_"$instance_name)
    echo "#sapsystem:instance:instance_no:appname:service_ip"
    echo "$SAPSYSTEMNAME:$instance_name:$instance_num:$appname:$service_ips"
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   listERSProperties
#
# Purpose:
#   To check locally for the given scs instance properties for SMIT screens
#
# Output:
#   <SID>:<SAP ERS Instance(s) Name(s)>:<Instance Nos.>:<Application Name>:
#    <Participating Nodes>
#    This function is called only from checkAndListERSPropertiesLocally
# Returns:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function listERSProperties {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset startProfiles
    typeset instance_name=$1
    typeset INSTANCE_NAME virt_ip instance_dir instance_no
    echo 
    getAllSAPInstanceStartupProfiles startProfiles
    for dir in "${!startProfiles[@]}"; do
        INSTANCE_NAME=$(getInstanceNameFromProfile ${startProfiles[$dir]})
        [[ $INSTANCE_NAME == $instance_name ]] && {

            virt_ip=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
                      $SAPEXEDIR/sappfpar pf=${startProfiles[$dir]} SAPLOCALHOST" 2>/dev/null)

            instance_no=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
                          $SAPEXEDIR/sappfpar pf=${startProfiles[$dir]} SAPSYSTEM" 2>/dev/null)

            instance_dir=$(/usr/bin/su - $SAPADMNUSR -c "env LANG=C  \
                                $SAPEXEDIR/sapcontrol \
                                -nr $instance_no \
                                -function ParameterValue DIR_INSTANCE \
                                -format script" 2>/dev/null | \
                                tail -n 1 | awk -F":" '{print $2}' 2>/dev/null)

            shared_vg=$(KLIB_AIX_get_vg_by_path $instance_dir)
            appname=$(echo "SAP_"$SAPSYSTEMNAME"_"$instance_name)
            echo "#sapsystem:instance:instance_no:appname:service_ip:shared_vg"
            echo "$SAPSYSTEMNAME:$instance_name:$instance_no:$appname:$virt_ip:$shared_vg"
            return 0
        }
    done
    echo "#sapsystem:instance:instance_no:appname:service_ip:shared_vg"
    echo ":::::::"
}


#----------------------------------------------------------------------------
# Function:
#   viewProperties
#
# Purpose:
#   General Purpose function for listing properties associated with an 
#   existing HACMP application name/id.  Used for the SMIT modify screens
#
# Arguments:
#   (1) Application Name / ID
#
# Return:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function viewProperties {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset appid=$1

    [[ -z $appid ]] && return 1

    set -a
    eval $(clquerysaapp -a $appid | grep COMPONENT_ID)
    set +a
    
    [[ "$COMPONENT_ID" == "SAPNW_SAPGFS" ]] && {
        viewGFSProperties $appid
        return $?
    }

    [[ "$COMPONENT_ID" == "SAPNW_ASINSTANCE" ]] && {
        viewASProperties $appid
        return $?
    }

    [[ "$COMPONENT_ID" == "SAPNW_SCSINSTANCE" ]] && {
        viewSCSProperties $appid
        return $?
    }
    
    [[ "$COMPONENT_ID" == "SAPNW_ERSINSTANCE" ]] && {
        viewERSProperties $appid
        return $?
    }
}
#----------------------------------------------------------------------------
# Function:
#   viewGFSProperties
#
# Purpose:
#   To list the properties used for configuring SAP GFS
#   for the SMIT view/modify screens
#
# Arguments:
#   (1) Application Name / ID
#
# Return:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function viewGFSProperties {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
    typeset appid=$1
    typeset primary takeover service_ip shared_vg export_dir mount_dir nodes sapsystem appname
    echo "#sapsystem:appname:primary:takeover:service_ip:shared_vg:export_dir:mount_dir"
    nodes=$(getNodes $appid)
    echo $nodes | read primary takeover
    sapsystem=$(getMetadata $appid SAPSYSTEMNAME)
    appname=$(getMetadata $appid APPLICATION_NAME)
    service_ip=$(getResource $appid SERVICE_LABEL)
    service_ip=$(echo $service_ip)
    shared_vg=$(getResource $appid VOLUME_GROUP)
    shared_vg=$(echo $shared_vg)
    export_dir=$(getResource $appid EXPORT_FILESYSTEM)
    export_dir=$(echo $export_dir)
    mount_dir=$(getResource $appid MOUNT_FILESYSTEM)
    echo "$sapsystem:$appname:$primary:$takeover:$service_ip:$shared_vg:$export_dir:$mount_dir"
    return 0
}

#----------------------------------------------------------------------------
# Function:
#   viewSCSProperties
#
# Purpose:
#   To list the properties used for configuring SAP SCS instance(s)
#   for the SMIT view/modify screens
#
# Arguments:
#   (1) Application Name / ID
#
# Return:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

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

    typeset primary takeover service_ips shared_vg sapsystem instances instance_nos
    typeset appid=$1
    typeset SAP_GLOBALS="SAP_GLOBALS"
    echo "#sapsystem:instance:instance_no:appname:primary:takeover:service_ip:shared_vg:Network_Name:db_rg:profile:exe_dir:start_timeout:start_delay:stop_timeout:stop_delay:ens_sync:is_nfs:export_dir:nfs_ip:is_ers_enabled:notification_level:xplatform:Start_failed:StartService_failed:nfs_failed:monitor_unabailable:gw_outage:sapadmuser:logger_logfile:notify:osconers:osconcs:osconapp"
    sapsystem=$(getMetadata $appid SAPSYSTEMNAME)
    instances=$(getMetadata $appid INSTANCE_NAMES | tr ' ' '_')
    instance_nos=$(getMetadata $appid INSTANCE_NUMBERS | tr ' ' '_')
    nodes=$(getNodes $appid)
    echo $nodes | read primary takeover
    
    setAttributesValues $appid

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

    if [[ $DBRG == "NONE" ]] 
    then
        DBRG=''
    fi 

    echo "$SAPSYSTEMNAME:$INSTANCE_NAMES:$INSTANCE_NUMBERS:$appid:$primary:$takeover:$VIRTUAL_IPS:$VOLUME_GROUP:$SERVICE_NETWORK:$DBRG:$PROFILE:$EXECUTABLE:$START_TIMEOUT:$START_DELAY:$STOP_TIMEOUT:$STOP_DELAY:$ENS_SYNC:$IS_NFS:$EXPORTS:$NFS_IP:$IS_ERS_ENABLED:$NOTIFICATION_LEVEL:$SA_SAP_XPLATFORM_LOGGING:$EC_START_FAILED:$EC_START_SERVICE_FAILED:$EC_START_NFS_FAILED:$EC_MONITOR_SAPSTARTSRV_UNAVAILABLE:$EC_MONITOR_FAILOVER_ON_GW_OUTAGE:$SAPADMUSER:$LOGGER_LOGFILE:$NOTIFY:$OSCON_ONOFF_ERS:$OSCON_ONOFF_CS:$OSCON_ONOFF_APP"
}

#----------------------------------------------------------------------------
# Function:
#   viewASProperties
#
# Purpose:
#   To list the properties used for configuring SAP Application Server instance
#   for the SMIT view/modify screens
#
# Arguments:
#   (1) Application Name / ID
#
# Return:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

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

    typeset primary takeover service_ip shared_vg sapsystem instances instance_nos
    typeset appid=$1
    typeset SAP_GLOBALS="SAP_GLOBALS"
    echo "#sapsystem:instance:instance_no:appname:primary:takeover:service_ip:shared_vg:Network_Name:db_rg:profile:exe_dir:start_timeout:start_delay:stop_timeout:stop_delay:ens_sync:is_nfs:export_dir:nfs_ip:notification_level:xplatform:Start_failed:StartService_failed:nfs_failed:monitor_unabailable:gw_outage:sapadmuser:logger_logfile:notify:osconers:osconcs:osconapp"
    sapsystem=$(getMetadata $appid SAPSYSTEMNAME)
    instance=$(getMetadata $appid INSTANCE_NAME)
    instance_no=$(getMetadata $appid INSTANCE_NUMBER)
    nodes=$(getNodes $appid)
    echo $nodes | read primary takeover

    
    setAttributesValues $appid

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

    if [[ $DBRG == "NONE" ]] 
    then
        DBRG=''
    fi 

    echo "$SAPSYSTEMNAME:$INSTANCE_NAMES:$INSTANCE_NUMBERS:$appid:$primary:$takeover:$VIRTUAL_IPS:$VOLUME_GROUP:$SERVICE_NETWORK:$DBRG:$PROFILE:$EXECUTABLE:$START_TIMEOUT:$START_DELAY:$STOP_TIMEOUT:$STOP_DELAY:$ENS_SYNC:$IS_NFS:$EXPORTS:$NFS_IP:$NOTIFICATION_LEVEL:$SA_SAP_XPLATFORM_LOGGING:$EC_START_FAILED:$EC_START_SERVICE_FAILED:$EC_START_NFS_FAILED:$EC_MONITOR_SAPSTARTSRV_UNAVAILABLE:$EC_MONITOR_FAILOVER_ON_GW_OUTAGE:$SAPADMUSER:$LOGGER_LOGFILE:$NOTIFY:$OSCON_ONOFF_ERS:$OSCON_ONOFF_CS:$OSCON_ONOFF_APP"

}

#----------------------------------------------------------------------------
# Function:
#   viewERSProperties
#
# Purpose:
#   To list the properties used for configuring SAP ERS instance(s)
#   for the SMIT view/modify screens
#
# Arguments:
#   (1) Application Name / ID
#
# Return:
#   0 on success
#   1 on failure
#----------------------------------------------------------------------------

function viewERSProperties {
    [[ $VERBOSE_LOGGING == "high" ]] && set -x
 
    typeset shared_vg
    typeset sapsystem instances instance_nos
    typeset appid=$1
    typeset SAP_GLOBALS="SAP_GLOBALS"
    echo "#sapsystem:instance:instance_no:appname:participating_nodes:service_ip:shared_vg:Network_Name:profile:exe_dir:start_timeout:start_delay:stop_timeout:stop_delay:ens_sync:is_nfs:export_dir:nfs_ip:notification_level:xplatform:Start_failed:StartService_failed:nfs_failed:monitor_unabailable:gw_outage:sapadmuser:logger_logfile:notify:osconers:osconcs:osconapp"

    sapsystem=$(getMetadata $appid SAPSYSTEMNAME)
    instances=$(getMetadata $appid INSTANCE_NAMES | tr ' ' '_')
    instance_nos=$(getMetadata $appid INSTANCE_NUMBERS | tr ' ' '_')
    nodes=$(getNodes $appid)
    

    setAttributesValues $appid

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

    echo "$SAPSYSTEMNAME:$INSTANCE_NAMES:$INSTANCE_NUMBERS:$appid:$nodes:$VIRTUAL_IPS:$VOLUME_GROUP:$SERVICE_NETWORK:$PROFILE:$EXECUTABLE:$START_TIMEOUT:$START_DELAY:$STOP_TIMEOUT:$STOP_DELAY:$ENS_SYNC:$IS_NFS:$EXPORTS:$NFS_IP:$NOTIFICATION_LEVEL:$SA_SAP_XPLATFORM_LOGGING:$EC_START_FAILED:$EC_START_SERVICE_FAILED:$EC_START_NFS_FAILED:$EC_MONITOR_SAPSTARTSRV_UNAVAILABLE:$EC_MONITOR_FAILOVER_ON_GW_OUTAGE:$SAPADMUSER:$LOGGER_LOGFILE:$NOTIFY:$OSCON_ONOFF_ERS:$OSCON_ONOFF_CS:$OSCON_ONOFF_APP"
}

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

typeset INSTANCE LOCAL_CHECK INSTANCE_TYPE SID
LOCAL_CHECK=false

typeset -A listPropertiesMethod
while getopts i:La:S: option; do
    case $option in
    a)
       typeset APPLICATION_ID
       APPLICATION_ID=$OPTARG
       viewProperties $APPLICATION_ID
       exit $?
    ;;
    i)
        INSTANCE=$OPTARG
    ;;
    L)
        LOCAL_CHECK=true
    ;;
    S)
        SID=$OPTARG
    ;;
    *)
    ;;
    esac
done

if [[ $INSTANCE == "GFS" ]];then
 INSTANCE_TYPE=GFS
fi

[[ $INSTANCE == D* || $INSTANCE == J* ]] && INSTANCE_TYPE=AS
[[ $INSTANCE == ASCS* || $INSTANCE == SCS* ]] && INSTANCE_TYPE=SCS
[[ $INSTANCE == ERS* ]] && INSTANCE_TYPE=ERS

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

   
[[ $LOCAL_CHECK == "false" ]] && {
    listPropertiesMethod=(
        [GFS]="checkGFSPropertiesGlobally"
        [AS]="checkASPropertiesGlobally"
        [SCS]="checkSCSPropertiesGlobally"
        [ERS]="checkERSPropertiesGlobally"
    )

    if [[ -z ${listPropertiesMethod[$INSTANCE_TYPE]} ]]; then
        exit 1
    fi
    ${listPropertiesMethod[$INSTANCE_TYPE]} $INSTANCE
    exit $?
}

typeset -A listPropertiesMethod
listPropertiesMethod=(
    [GFS]="checkAndListGFSPropertiesLocally"
    [AS]="checkAndListASPropertiesLocally"
    [SCS]="checkAndListSCSPropertiesLocally"
    [ERS]="checkAndListERSPropertiesLocally"
)

if [[ -z ${listPropertiesMethod[$INSTANCE_TYPE]} ]]; then
    exit 1
fi

${listPropertiesMethod[$INSTANCE_TYPE]} $INSTANCE
exit $?
