#!/bin/bash
#
# THIS SCRIPT PROVIDES TARGETED GATHERING BASED ON NS, PLAN AND VM NAME
#
# NOTICE: THIS FILE IS NOT INCLUDED IN THE DEFAULT GATHER SCRIPT
#
# Can be executed by: oc adm must-gather --image quay.io/konveyor/forklift-must-gather:latest -- NS=foo PLAN=bar VM=baz /usr/bin/targeted
#

unset KUBECONFIG

# Explore where Forklift is installed
for localns in $(/usr/bin/oc get forkliftcontrollers.forklift.konveyor.io --all-namespaces --no-headers | awk '{print $1}'); do

  # Collect the Forklift and Kubevirt related CRs
  echo "Targeted gathering for Forklift in namespaces [${localns}]"
  /usr/bin/targeted_crs ${localns} || exit 1

  # Collect the logs
  echo "Gathering logs for namespaces [${localns}]"
  /usr/bin/targeted_logs ${localns}
done

# Remove empty files to ensure that the directory structure doesn't confuse user with not relevant entries
echo "Cleaning must-gather directory structure..."
find /must-gather -type f -empty -print -delete
find /must-gather -type d -empty -print -delete

# Tar all must-gather artifacts for faster transmission 
echo "Tarring must-gather artifacts..."
archive_path="/must-gather-archive"
mkdir -p ${archive_path}
tar -zcf ${archive_path}/must-gather.tar.gz /must-gather/
rm -rf /must-gather/*
mv ${archive_path}/must-gather.tar.gz /must-gather/
rmdir ${archive_path}
echo "Created /must-gather/must-gather.tar.gz"

echo "Waiting for copy phase..."
exit 0
