#!/bin/bash
source pwait
max_parallelism=10

# Cluster passed in from main gather
cluster=$1
logs_since=$2
timeout=$3
shift
shift
shift
namespaces=("$@")


# Collect all Pod logs from namespaces where OADP operator is installed
for ns in ${namespaces[@]}; do
  # Gather Pod associated logs
  /usr/bin/gather_logs_pods ${cluster} ${ns} ${logs_since} ${max_parallelism} &

  # Gather logs for each oadp operator instance
  for dpa in $(oc get dpa --namespace ${ns} --no-headers | awk '{print $1}'); do
    plan_path="/must-gather/clusters/${cluster}/namespaces/${ns}/oadp.openshift.io/dpa-${dpa}"
    mkdir -p ${plan_path}
    
      for backup in $(oc get backup --namespace ${ns} --no-headers | awk '{print $1}'); do
        # Gather backup
        backup_path="${plan_path}/backup-${backup}"
        mkdir -p ${backup_path}
        /usr/bin/gather_logs_backup ${cluster} ${ns} ${logs_since} ${max_parallelism} ${backup} ${backup_path} ${timeout} &
        pwait $max_parallelism
        for pvb in $(oc get podvolumebackup --namespace ${ns} -l "velero.io/backup-name"="${backup}" --no-headers | awk '{print $1}'); do
          # Gather PVB
          pvb_path="${backup_path}/podvolumebackup-${pvb}"
          mkdir -p ${pvb_path}
          /usr/bin/gather_logs_pvb ${cluster} ${ns} ${logs_since} ${max_parallelism} ${pvb} ${pvb_path} &
          pwait $max_parallelism
        done
      done
      
      for restore in $(oc get restore --namespace ${ns} --no-headers | awk '{print $1}'); do
        # Gather restore
        restore_path="${plan_path}/restore-${restore}"
        mkdir -p ${restore_path}
        /usr/bin/gather_logs_restore ${cluster} ${ns} ${logs_since} ${max_parallelism} ${restore} ${restore_path} ${timeout} &
        pwait $max_parallelism
        for pvr in $(oc get podvolumerestore --namespace ${ns} -l "velero.io/restore-name"="${restore}" --no-headers | awk '{print $1}'); do
          # Gather PVR
          pvr_path="${restore_path}/podvolumerestore-${pvr}"
          mkdir -p ${pvr_path}
          /usr/bin/gather_logs_pvr ${cluster} ${ns} ${logs_since} ${max_parallelism} ${pvr} ${pvr_path} &
          pwait $max_parallelism
        done
      done
    
  done
done

# Wait for all background jobs to complete
wait