#!/bin/bash
#
# Copyright contributors to the ibm-storage-odf-operator project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Command line argument
ODF_NAMESPACE=$1
IBMCSI_NAMESPACE=$2
BASE_COLLECTION_PATH=$3
FILTER_STRING=$4

# Use must-gather as base path if no argument is passed
if [ "${BASE_COLLECTION_PATH}" = "" ]; then
    BASE_COLLECTION_PATH="must-gather"
fi
mkdir -p ${BASE_COLLECTION_PATH}

# Create dir for secret
LOG_PATH="${BASE_COLLECTION_PATH}/secret/"
mkdir -p ${LOG_PATH}

echo "INFO: Gathering Secrets"
ODF_SECRETS=($(oc -n ${ODF_NAMESPACE} get secret --no-headers -o custom-columns=":metadata.name" -l odf="storage.ibm.com"))

if [ "${FILTER_STRING}" != "" ]; then
    for ODF_SECRET in ${ODF_SECRETS[@]}; do
        if echo ${ODF_SECRET} | grep -Eq ${FILTER_STRING}; then
            echo "INFO: Gathering Secret ${ODF_SECRET}"
            oc -n ${ODF_NAMESPACE} get secret -o yaml ${ODF_SECRET} > "${LOG_PATH}"/get_"${ODF_SECRET}".yaml 2>&1
            oc -n ${ODF_NAMESPACE} describe secret ${ODF_SECRET} > "${LOG_PATH}"/describe_"${ODF_SECRET}".log 2>&1
        fi
    done

else

    for ODF_SECRET in ${ODF_SECRETS[@]}; do
        echo "INFO: Gathering Secret ${ODF_SECRET}"
        oc -n ${ODF_NAMESPACE} get secret -o yaml ${ODF_SECRET} > "${LOG_PATH}"/get_"${ODF_SECRET}".yaml 2>&1
        oc -n ${ODF_NAMESPACE} describe secret ${ODF_SECRET} > "${LOG_PATH}"/describe_"${ODF_SECRET}".log 2>&1
    done

fi
