#!/bin/bash
source pwait
max_parallelism=10

# Namespaces passed in from main gather
namespaces=$1

# Resource list
resources=()

# Dump forklift and kubevirt CRs
for component in forklift kubevirt; do
  for i in $(/usr/bin/oc get crd | grep ${component} | awk '{print $1}'); do
    resources+=($i)
  done

  echo "Starting collection of: [${resources[@]}]"

  # we use nested loops to nicely output objects partitioned per namespace, kind
  for resource in ${resources[@]}; do
    echo "Collecting ${resource}"
    /usr/bin/oc get ${resource} --all-namespaces -o custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace --no-headers 2> /dev/null | \
    while read ocresource; do
      ocobject=$(echo $ocresource | awk '{print $1}')
      ocproject=$(echo $ocresource | awk '{print $2}')
      if [ -z "${ocproject}" ]|[ "${ocproject}" == "<none>" ]; then
        object_collection_path=must-gather/cluster-scoped-resources/${resource}
        mkdir -p ${object_collection_path}
        /usr/bin/oc get ${resource} -o yaml ${ocobject} &> ${object_collection_path}/${ocobject}.yaml &
      else
        object_collection_path=must-gather/namespaces/${ocproject}/crs/${resource}
        mkdir -p ${object_collection_path}
        /usr/bin/oc get ${resource} -n ${ocproject} -o yaml ${ocobject} &> ${object_collection_path}/${ocobject}.yaml &
      fi
      pwait $max_parallelism
    done
  done
done

wait
