#!/bin/bash
# Expect base collection path as an argument
BASE_COLLECTION_PATH=$1

# Use PWD as base path if no argument is passed
if [ "${BASE_COLLECTION_PATH}" = "" ]; then
    BASE_COLLECTION_PATH=$(pwd)
fi

# Expect time option as an argument
SINCE_TIME=$2

# Command List
commands_get=()

# collect oc output of OC get commands
commands_get+=("csidriver")
commands_get+=("pv")
commands_get+=("sc")
commands_get+=("nodes -o wide --show-labels")
commands_get+=("clusterversion")
commands_get+=("infrastructures.config")
commands_get+=("clusterrole")
commands_get+=("clusterrolebinding")
commands_get+=("scc")

# collect yaml output of OC commands
oc_yamls=()
oc_yamls+=("csidriver")
oc_yamls+=("pv")
oc_yamls+=("sc")
oc_yamls+=("nodes")
oc_yamls+=("clusterversion")
oc_yamls+=("infrastructures.config")
oc_yamls+=("clusterrole")
oc_yamls+=("clusterrolebinding")
oc_yamls+=("scc")


# collect describe output of OC commands
commands_desc=()
commands_desc+=("csidriver")
commands_desc+=("pv")
commands_desc+=("sc")
commands_desc+=("nodes")
commands_desc+=("clusterversion")
commands_desc+=("infrastructures.config")
commands_desc+=("clusterrole")
commands_desc+=("clusterrolebinding")
commands_desc+=("scc")

# collection path for OC commands
mkdir -p "${BASE_COLLECTION_PATH}/cluster-scoped-resources/oc_output/"

# Run the Collection of Resources oc get to list
for command_get in "${commands_get[@]}"; do
     echo "collecting oc command ${command_get}" | tee -a "${BASE_COLLECTION_PATH}/gather-debug.log"
     COMMAND_OUTPUT_FILE=${BASE_COLLECTION_PATH}/cluster-scoped-resources/oc_output/get_${command_get// /_}
     # shellcheck disable=SC2086
     { oc get ${command_get}; } >> "${COMMAND_OUTPUT_FILE}"
done

# Run the Collection of Resources oc yaml to list
for oc_yaml in "${oc_yamls[@]}"; do
    { oc adm --dest-dir="${BASE_COLLECTION_PATH}" inspect "${oc_yaml}" --"${SINCE_TIME}"; } >> "${BASE_COLLECTION_PATH}"/gather-debug.log 2>&1
done

# Run the Collection of Resources oc describe to list
for command_desc in "${commands_desc[@]}"; do
     echo "collecting oc command ${command_desc}" | tee -a "${BASE_COLLECTION_PATH}/gather-debug.log"
     COMMAND_OUTPUT_FILE=${BASE_COLLECTION_PATH}/cluster-scoped-resources/oc_output/desc_${command_desc// /_}
    { oc describe "${command_desc}"; } >> "${COMMAND_OUTPUT_FILE}"
done
