#!/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 service
LOG_PATH="${BASE_COLLECTION_PATH}/service/"
mkdir -p ${LOG_PATH}

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

if [ "${FILTER_STRING}" != "" ]; then

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

else

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

fi
