#!/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_list_backup_files.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_list_backup_files

=head1 SYNOPSIS

 clmgr query backup_files \
             BUCKET_NAME=<bucket_name> \
             RG_NAME=<rg_name> \
             [ START_TIME=<yyyy-mm-ddThh> ] \
             [ END_TIME=<yyyy-mm-ddThh> ]  
 
 clmgr query backup_files \
             BUCKET_NAME=<bucket_name> \
             [ RG_NAME=<rg_name> ] \
             [ START_TIME=<yyyy-mm-ddThh> ] \
             [ END_TIME=<yyyy-mm-ddThh> ] 
 
  clmgr query backup_files \
             RG_NAME=<rg_name> \
             [ BUCKET_NAME=<bucket_name> ] \
             [ START_TIME=<yyyy-mm-ddThh> ] \
             [ END_TIME=<yyyy-mm-ddThh> ]
 
 backup_files => bf, backup_f*

=head1 DESCRIPTION

 Displays the cloud backup files.

=head1 ARGUMENTS

 1. bucket_name [OPTIONAL] [String]
    Bucket Name to list the files in the bucket. For aws, bucket name refers to S3 bucket.
 2. rg_name [OPTIONAL] [String]
    It is used to list the files which are specific to provided Resource Group.
 3. start_time [OPTIONAL] [String]
    If you provide the start time it will list the files which are uploaded only after start time.
 4. end_time [OPTIONAL] [String]
    If you provide the end time it will list the files which are uploaded from start time to end time.

=cut
} # End of POD-formatted documentation.


function KLIB_HACMP_list_backup_files {
    . $HALIBROOT/log_entry "$0()" "$CL"

    typeset bucket_name=$1
    typeset rg_name=$2
    typeset start_time=$3
    typeset end_time=$4

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

    #===================================
    : Declare and initialize variables
    #===================================
    typeset -i rc=$RC_UNKNOWN
    typeset available_rgs="" # To store the backup rg's
    typeset backup_type="" # To store the backup method, which is cloud or remote
    typeset cloud_rgs="" # To store the backup rgs which are configured for cloud
    typeset output=""
    typeset service="" # To store CLOUD service information
    typeset bOpt="" rOpt="" sOpt="" eOpt="" cOpt=""
    typeset configured_bucket="" # To store the bucket name which is configured for rg
    typeset service_list=""

    #====================================
    : 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
    elif [[ -z $bucket_name && -z $rg_name ]]
    then
        cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1202 "\nERROR: Provide resource group (RG_NAME) or bucket name (BUCKET_NAME) or both.\n\n" 1>&2
        rc=$RC_MISSING_INPUT
    elif [[ -z $start_time && -n $end_time ]]
    then
        cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1203 "\nERROR: Provide start time with end time.\n\n" 1>&2
        rc=$RC_MISSING_INPUT
    else
        print -- "$0()[$LINENO]($SECONDS): cl_cbm_list" >>$CLMGR_TMPLOG # Always log command result
        available_rgs=$(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 ));then
            cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1197 "\nERROR: No resource group configured for backup.\n\n" 1>&2
            rc=$RC_ERROR
        fi
    fi

    # Get the list of backup rgs which are configured for cloud storage.
    for rg in $available_rgs
    do
        backup_type=$(LANG=C cl_cbm_list $rg | grep -w Backup_method | cut -f2 -d'=' | sed -e 's/^ *//')
        if [[ $backup_type == "cloud" ]]
        then
            cloud_rgs="$cloud_rgs $rg"
        fi
    done

    # Validate inputs
    if (( rc == RC_UNKNOWN || rc == RC_SUCCESS ))
    then
        if [[ -n $rg_name ]]
        then
            :
            # Checking the given rg is configured for cloud backup or not
            :
            echo $cloud_rgs | grep -wq $rg_name
            if (( $? == 0 ))
            then
                :
                # If bucket name not provided then take the bucket name from the xml file where we are storing the backup configuration
                :
                output=$(LANG=C cl_cbm_list $rg_name 2>>$CLMGR_TMPLOG)
                service_list=$(echo "$output" | grep -w "Cloud_service" | cut -f 2 -d '=' | tr -d ' ')
                if [[ -z $bucket_name ]]
                then
                    bucket_name=$(echo "$output" | grep -w "Bucket_name" | cut -f 2 -d '=' | tr -d ' ')
                else
                    configured_bucket=$(echo "$output" | grep -w "Bucket_name" | cut -f 2 -d '=' | tr -d ' ')
                    if [[ $bucket_name != $configured_bucket ]]
                    then
                        cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1209 "\nERROR: The provided bucket, %1\$s, is invalid because the given resource group, %2\$s, is configured with a different bucket name, %3\$s.\n\n" "$bucket_name" "$rg_name" "$configured_bucket" 1>&2
                        rc=$RC_ERROR
                    fi 
                fi                
            else
                cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1204 "\nERROR: The provided resource group, %1\$s, is not configured for cloud backup.\n\n" "$rg_name" 1>&2
                cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1208 "Available resource groups which are configured for cloud are:\n\n" "$cloud_rgs" 1>&2
                output=$(echo "$cloud_rgs" | tr " " "\n")
                print -u2 "$output" 
                rc=$RC_INCORRECT_INPUT
            fi
        elif [[ -n $bucket_name ]]
        then
            # Get the list of rgs which are configured with provided bucket
            for rg in $cloud_rgs
            do
                output=$(LANG=C cl_cbm_list $rg 2>>$CLMGR_TMPLOG)
                configured_bucket=$(echo "$output" | grep -w "Bucket_name" | cut -f 2 -d '=' | tr -d ' ')
                service=$(echo "$output" | grep -w "Cloud_service" | cut -f 2 -d '=' | tr -d ' ')
                if [[ $bucket_name == $configured_bucket ]]
                then
                    echo $service_list | grep -q $service
                    if (( $? != 0 ))
                    then
                        service_list="$service_list $service"
                    fi
                fi
          done
          if [[ -z $service_list ]]
          then
              cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1319 "\nERROR: The provided bucket %1\$s does not exist in any of the cloud configured backup profiles.\n\n" "$bucket_name" 1>&2  
          fi 
        fi

        # Verify whether the provided start and end times are in proper format.
        if [[ -n $start_time ]]
        then
            validate_time $start_time
            if (( $? != RC_SUCCESS  ))
            then
                cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1206 "\nERROR: The provided start time format is invalid.\n\n" 1>&2
                cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1205 "\nERROR: Provide time in yyyy-mm-ddThh format.\n\n" 1>&2
                rc=$RC_ERROR
            fi
        fi

        if [[ -n $end_time ]]
        then
            validate_time $end_time
            if (( $? != RC_SUCCESS  ))
            then
                cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1207 "\nERROR: The provided end time format is invalid.\n\n" 1>&2
                cl_dspmsg -s $CLMGR_SET $CLMGR_MSGS 1205 "\nERROR: Provide time in yyyy-mm-ddThh format.\n\n" 1>&2
                rc=$RC_ERROR
            fi
        fi
    fi

    # Calling list utility
    if (( rc == RC_UNKNOWN || rc == RC_SUCCESS ))
    then
        [[ -n $bucket_name ]] && bOpt="-b $bucket_name"
        [[ -n $start_time ]] && sOpt="-s $start_time"
        [[ -n $end_time ]] && eOpt="-e $end_time"
        [[ -n $rg_name ]] && rOpt="-r $rg_name"

        for service in $service_list
        do
            cOpt="-c $service"
            print -- "$0()[$LINENO]($SECONDS): cl_cbm_cloud_utils -o query $rOpt $bOpt $sOpt $eOpt $cOpt" >>$CLMGR_TMPLOG # Always log command result
            LANG=C cl_cbm_cloud_utils -o query $rOpt $bOpt $sOpt $eOpt $cOpt
            rc=$?
            print -- "$0()[$LINENO]($SECONDS): cl_cbm_cloud_utils -o query $rOpt $bOpt $sOpt $eOpt $cOpt RC:$rc" >>$CLMGR_TMPLOG # Always log command result
            if (( rc != RC_SUCCESS ))
            then
                rc=$RC_ERROR
                break
            fi
        done
    fi

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

#==============================================================================
#
# Name:        validate_time
#
# Description: This function will validates whether the user provided time is 
#              proper format or not.
#
# Inputs:      start_time or end_time 
#
# Outputs:     None 
#
# Returns:     Zero if the provided time format is correct. 
#              Otherwise a non-zero value is returned.
#
#==============================================================================
function validate_time {
   . $HALIBROOT/log_entry "$0()" "$CL"
   [[ $CLMGR_LOGGING == 'med' ]] && set +x  # Only trace param values

   #===================================
   : Declare and initialize variables
   #===================================
   typeset usertime=""
   typeset datedelimiter=""
   usertime=$1
   
   if (( ${#usertime} != 13 ))
   then
       return $RC_ERROR
   fi

   # Check for 'T' in the timestamp format
   datedelimiter=$(echo $usertime | cut -c11)
   if [[ -z $datedelimiter || $datedelimiter != 'T' ]]
   then
       return $RC_ERROR
   fi

   # Extract year, month, date and time to perform validation
    echo "$usertime" | cut -f1 -d'T' | IFS=- read year month day
    time=$(echo "$usertime" | cut -f2 -d'T')

   if [[ -z $time || -z $day || -z $month || -z $year ]]
   then
       return $RC_ERROR
   fi

   # Check if all the data provided like day month time etc are digits or not
    if [[ $year != +([[:digit:]]) || $month != +([[:digit:]]) || $day != +([[:digit:]]) || $time != +([[:digit:]]) ]]
    then
        return $RC_ERROR
    fi

} #End of "validate_time()"
