#!/bin/ksh93
#  ALTRAN_PROLOG_BEGIN_TAG                                                    
#  This is an automatically generated prolog.                                  
#                                                                              
#  Copyright (C) Altran ACT S.A.S. 2018,2019,2020,2021.  All rights reserved.  
#                                                                              
#  ALTRAN_PROLOG_END_TAG                                                      
#                                                                              
# @(#)  5f56dbd 43haes/lib/ksh93/hacmp/KLIB_HACMP_get_backup_profile_attributes.sh, 726, 2147A_aha726, Mar 08 2021 04:44 PM

# Start of POD-formatted documentation. Viewing suggestions:
#      perldoc <FILENAME>
#      pod2text -c <FILENAME>
#      pod2text -c --code <FILENAME>
#      pod2html <FILENAME>
function devDoc {
: <<'=cut' >/dev/null 2>&1

=head1 NAME

 KLIB_HACMP_get_backup_profile_attributes

=head1 SYNOPSIS

 clmgr query backup_profile {<resource_group>[,<resource_group#2>,...]}

 query => get, list, ls, show
 backup_profile => bp, backup_p, replication_profile

=head1 DESCRIPTION

 Retrieves the backup profile configuration data for one or more resource groups

=head1 ARGUMENTS

 1. properties [REQUIRED] [hash ref]
 An associative array within which data about the
 created object can be returned to the caller.

 2. resource_group [REQUIRED] [string]
 Resource group name can be single or multiple resource groups.

=head1 RETURN

 0: no errors were detected; the operation appears to have been successful
 1: a general error has occurred
 2: a specified resource does not exist, or could not be found
 3: some required input was missing
 4: some detected input was incorrect in some way
 5: a required dependency does not exist
 6: a specified search failed to match any data

=cut
} # End of POD-formatted documentation.

#============================================================================
#
# Name:        KLIB_HACMP_get_backup_profile_attributes
#
# Description: This is the main, FPATH function that is invoked by clmgr
#              to get backup_profile configuration. The cl_cbm_list utility is invoked
#              to extract the necessary data from backup configuration xml file.
#
# Inputs:      See the "devDoc()" function at the top of this file.
#
# Outputs:     The properties hash is populated. The only other outputs are
#              any error messages that might be needed.
#
# Returns:     Zero if no errors are detected. Otherwise, an appropriate
#              non-zero value is returned. Refer to the "RETURN" section
#              of the "devDoc()" function at the top of this file for
#              the standard return code values/meanings for clmgr.
#
#============================================================================
function KLIB_HACMP_get_backup_profile_attributes {
    . $HALIBROOT/log_entry "$0()" "$CL"
    : version=@(#)  5f56dbd 43haes/lib/ksh93/hacmp/KLIB_HACMP_get_backup_profile_attributes.sh, 726, 2147A_aha726, Mar 08 2021 04:44 PM
    : INPUTS: $*

    typeset rgs=${1//\"/}
    [[ -z $TAB ]] && TAB=$'\t'

    # Get the "properties" associative array reference, and initialize it
    if [[ -z $2 ]] || [[ -n $CLMGR_LOGGING && $2 == "|" ]]; then
        rgs=
        typeset -n properties=$1
    else
        typeset -n properties=$2
    fi

    [[ $CLMGR_LOGGING == 'med' ]] && set +x  # Only trace param values

    #===================================
    : Declare and initialize variables
    #===================================
    for k in ${!properties[*]}; do unset properties[$k]; done
    typeset -i INDEX=0 rc=$RC_UNKNOWN
    typeset enable_backup= rg= volume_group= replicated_resources= target_location= backup_method= cloud_service= compression= storage=""
    typeset bucket_name=""
    typeset backup_schedule= notify_method= encryption= RGS= output= resource_group= unknown_rg= available_rg= backup_progress= next_backup_schedule=
    typeset -i backup_frequency=
    typeset -i inc_backup_freq=
    typeset -A queries

    #===================================================
    : Check for any specified attribute=value pairs.
    : If any are found, use those to query the output.
    #===================================================
    while (( $# > 0 )); do
        value="$1"
        if [[ $value == *=* ]]; then
            attr=${value%%=*}  # "attr" makes this uppercase
            queries[$attr]="${value#*=}"
        fi
        shift
    done

    #====================================
    : Check python is installed or not
    #====================================
    LANG=C cl_get_python_version 2>&1 >>/dev/null
    rc=$?
    if (( $rc != 0 )); then
        cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1315 "\nERROR: Python must be installed for using backup feature.\n\n" 1>&2
        log_return_msg "$rc" "$0()" "$LINENO"
        return $rc
    fi

    #================================================================
    : Check for a defined cluster. No need to continue without one.
    #================================================================
    CL=$LINENO isClusterDefined
    if (( $? != RC_SUCCESS )); then
        rc=$RC_MISSING_DEPENDENCY
    else
        print -- "$0()[$LINENO]($SECONDS): cl_cbm_list" >>$CLMGR_TMPLOG # Always log command result
        available_rg=$(LANG=C cl_cbm_list 2>>$CLMGR_TMPLOG)
        rc=$?
        print -- "$0()[$LINENO]($SECONDS): cl_cbm_list RC:$rc" >>$CLMGR_TMPLOG # Always log command result
        if (( $rc != RC_SUCCESS && $rc > 2 ));then
            cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1197 "\nERROR: No resource group configured for backup.\n\n" 1>&2
            rc=$RC_ERROR
        else
            rc=$RC_SUCCESS
        fi
    fi
    #=======================================
    : Make sure we have something to query
    #=======================================
    if  (( $rc == RC_SUCCESS )) && [[ -n $rgs ]]; then
        [[ $rgs != *,* ]] && unset INDEX
        for rg in ${rgs//,/ }
        do
            echo "$available_rg" | grep -wq $rg
            rc=$?
            if (( $rc != RC_SUCCESS ));then
                unknown_rg=${unknown_rg:+$unknown_rg,}$rg
            else
                RGS="${RGS:+$RGS }$rg"
            fi
        done
        if [[ -n $unknown_rg ]];then
            cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1191 "\nERROR: Resource group \"%1\$s\" not configured for backup.\n\n" "$unknown_rg" 1>&2
            cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1192 "Configured resource groups for backup:\n\n" 1>&2
            output=$(echo "$available_rg" | sed "s/^/$TAB/g")
            print -u2 "$output"
            print -u2 ""
            rc=$RC_NOT_FOUND
        fi
    elif (( $rc == RC_SUCCESS )) && (( CLMGR_VERBOSE || ${#queries[*]} > 0 )); then
        for rg in $available_rg
        do
            RGS="${RGS:+$RGS }$rg"
        done
    fi
    (( rc != RC_SUCCESS && rc != RC_UNKNOWN )) && unset RGS


    #================================================================
    : Populate the return hash with the retrieved attributes/values
    #================================================================
    for rg in $RGS
    do
        print -- "$0()[$LINENO]($SECONDS): cl_cbm_list $rg" >>$CLMGR_TMPLOG # Always log command result
        output=$(LANG=C cl_cbm_list "$rg" 2>>$CLMGR_TMPLOG)
        rc=$?
        print -- "$0()[$LINENO]($SECONDS): cl_cbm_list $rg RC:$rc" >>$CLMGR_TMPLOG # Always log command result
        # Resource group configured in CBM
        if (( $rc != RC_SUCCESS ));then
            print -- "$0()[$LINENO]($SECONDS): cl_cbm_list $rg RC:$rc output=$output" >>$CLMGR_TMPLOG # Always log command result
            cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1191 "\nERROR: \"%1\$s\" Resource group not configured for backup.\n\n" "$rg" 1>&2
            rc=$RC_ERROR
        else
            resource_group=$(echo "$output" | grep -w "Resource_group" | cut -f 2 -d '=')
            resource_group=${resource_group// /} # removes space
            enable_backup=$(echo "$output" | grep -w "Enable_backup" | cut -f 2 -d '=')
            enable_backup=${enable_backup// /} # removes space
            volume_group=$(echo "$output" | grep -w "Volume_group" | cut -f 2 -d '=')
            replicated_resources=$(echo "$output" | grep -w "Replicated_resources" | cut -f 2 -d '=')
            storage=$(echo "$output" | grep -w "Storage_system" | cut -f2 -d '=')
            bucket_name=$(echo "$output" | grep -w "Bucket_name" | cut -f2 -d '=')
            bucket_name=${bucket_name// /} # removes space
            bucket_name=${bucket_name//\"\"/} # removes quotes
            target_location=$(echo "$output" | grep -w "Target_location" | cut -f 2 -d '=')
            target_location=${target_location// /} # removes space
            target_location=${target_location//\"\"/} # removes quotes
            backup_method=$(echo "$output" | grep -w "Backup_method" | cut -f 2 -d '=')
            backup_method=${backup_method// /} # removes space
            cloud_service=$(echo "$output" | grep -w "Cloud_service" | cut -f 2 -d '=')
            cloud_service=${cloud_service// /} # removes space
            cloud_service=${cloud_service//\"\"/} # removes quotes
            compression=$(echo "$output" | grep -w "Compression" | cut -f 2 -d '=')
            compression=${compression// /} # removes space
            compression=${compression//\"\"/} # removes quotes
            backup_frequency=$(echo "$output" | grep -w "Backup_frequency" | cut -f 2 -d '=')
            backup_frequency=${backup_frequency// /} # removes space
            backup_schedule=$(echo "$output" | grep -w "Backup_schedule" | cut -f 2 -d '=')
            backup_schedule=${backup_schedule// /} # removes space
            inc_backup_freq=$(echo "$output" | grep -w "Inc_backup_freq" | cut -f 2 -d '=')
            inc_backup_freq=${inc_backup_freq// /} # removes space
            notify_method=$(echo "$output" | grep -w "Notify_method" | cut -f 2 -d '=')
            notify_method=${notify_method// /} # removes space
            notify_method=${notify_method//\"\"/} # removes quotes
            encryption=$(echo "$output" | grep -w "Encryption" | cut -f 2 -d '=')
            encryption=${encryption// /} # removes space

            # Get backup_progress and next backup schedule 
            print -- "$0()[$LINENO]($SECONDS): cl_cbm_backup_progress $rg" >>$CLMGR_TMPLOG # Always log command result
            output=$(LC_ALL=C cl_cbm_backup_progress "$rg" 2>>$CLMGR_TMPLOG)
            rc=$?
            print -- "$0()[$LINENO]($SECONDS): cl_cbm_backup_progress $rg RC:$rc" >>$CLMGR_TMPLOG # Always log command result
            if (( $rc != RC_SUCCESS ));then
                print -- "$0()[$LINENO]($SECONDS): cl_cbm_backup_progress $rg RC:$rc output=$output" >>$CLMGR_TMPLOG # Always log command result
            else
                # grep for 'copying', if any of the backup process in copying state.
                backup_progress=$(echo $output | grep -w "copying")
                # Get next backup schedule in date,hrs:mins:secs format
                #f5 - date,hrs f6 - mins f7 - secs
                next_backup_schedule=$(echo $output | cut -d':' -f5,6,7)
            fi

            if [[ $backup_method == "cloud" ]]
            then
                properties[BUCKET_NAME$INDEX]=$bucket_name
                properties[TARGET_LOCATION$INDEX]=$target_location
                properties[CLOUD_SERVICE$INDEX]=$cloud_service
                properties[COMPRESSION$INDEX]=$compression
                properties[BACKUP_FREQUENCY$INDEX]=$backup_frequency
                properties[BACKUP_SCHEDULE$INDEX]=$backup_schedule
                properties[INC_BACKUP_FREQ$INDEX]=$inc_backup_freq
                properties[ENCRYPTION$INDEX]=$encryption
            fi
            properties[RESOURCE_GROUP$INDEX]=$resource_group
            properties[ENABLE_BACKUP$INDEX]=$enable_backup
            properties[VOLUME_GROUP$INDEX]=$volume_group
            properties[REPLICATED_RESOURCES$INDEX]=$replicated_resources
            properties[STORAGE_NAME$INDEX]=$storage
            properties[BACKUP_METHOD$INDEX]=$backup_method
            properties[NOTIFYMETHOD$INDEX]=$notify_method
            properties[NEXT_BACKUP_SCHEDULE$INDEX]=$next_backup_schedule 
            if [[ -z $backup_progress ]]
            then
                properties[BACKUP_PROGRESS$INDEX]="None"
            else
                properties[BACKUP_PROGRESS$INDEX]="in progress"
            fi

            rc=$RC_SUCCESS
        fi
        #==============================================================
        : Even if there is no value for a given attribute, we want to
        : display a placeholder for it, so the customer always sees a
        : consistent, complete set of attributes.
        #==============================================================
        for key in ${_COLON_ATTR_ORDER[backup_profile]}; do
            if [[ $key == "BACKUP_SCHEDULE" && $CLMGR_GUI == "SMIT" ]]; then
                # Appending #! to : to escape : while parsing to smit
                backup_schedule=${backup_schedule//:/#!:}
                properties[$key$INDEX]=${backup_schedule}
            fi
            if [[ -z ${properties[$key$INDEX]} ]]; then
                properties[$key$INDEX]=""
            fi
        done
        (( INDEX++ ))
        [[ $INDEX == *0 ]] && (( INDEX++ ))
    done

    #==========================================================
    : If any searches/filters were specified, handle them now 
    #==========================================================
    if (( $rc == RC_SUCCESS && ${#queries[*]} > 0 )); then
        CL=$LINENO search_properties queries properties
        rc=$?
    fi

    (( rc == RC_SUCCESS )) && CL=$LINENO prune_indexes properties

    log_return_msg "$rc" "$0()" "$LINENO"
    return $?
} # End of "KLIB_HACMP_get_backup_profile_attributes()"

#================================================
# The following, commented line enforces coding
# standards when this file is edited via vim.
#================================================
# vim:tabstop=4:shiftwidth=4:expandtab:smarttab
#================================================
