#!/bin/bash
BASE_COLLECTION_PATH="must-gather"
mkdir -p ${BASE_COLLECTION_PATH}

# Command line argument
SINCE_TIME=$1

# timestamp for starting of the script
START_TIME=$(date +%r)
start=$(date +%s)
printf "collection started at: %s \n" "${START_TIME}" >> ${BASE_COLLECTION_PATH}/gather-debug.log 2>&1

# Call pre-install.sh
pre-install.sh

# Call other gather scripts
gather_namespaced_resources ${BASE_COLLECTION_PATH} "${SINCE_TIME}"
gather_clusterscoped_resources ${BASE_COLLECTION_PATH} "${SINCE_TIME}"
gather_noobaa_resources ${BASE_COLLECTION_PATH} "${SINCE_TIME}"

storageClusterPresent=$(oc get storagecluster -n openshift-storage -o go-template='{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}')
externalStorageClusterPresent=$(oc get storagecluster -n openshift-storage -o go-template='{{range .items}}{{.spec.externalStorage.enable}}{{"\n"}}{{end}}')

if [ "${externalStorageClusterPresent}" == true ]; then
    echo "Collecting limited ceph logs since external cluster is present" | tee -a  "${BASE_COLLECTION_PATH}"/gather-debug.log
    gather_common_ceph_resources "${BASE_COLLECTION_PATH}" "${SINCE_TIME}"
elif [ -z "${storageClusterPresent}" ]; then
    echo "Skipping ceph collection as Storage Cluster is not present" | tee -a  "${BASE_COLLECTION_PATH}"/gather-debug.log
else
    echo "Collecting entire ceph logs" | tee -a "${BASE_COLLECTION_PATH}"/gather-debug.log
    gather_ceph_resources ${BASE_COLLECTION_PATH} "${SINCE_TIME}"
fi

# Call post-uninstall.sh
post-uninstall.sh

# timestamp for ending of the script
END_TIME=$(date +%r)
end=$(date +%s)
totalTime=$((end-start))
{
    printf "total time taken by collection was %s seconds \n" ${totalTime}
    printf "collection ended at: %s \n" "${END_TIME}"
    echo "deleting empty files"

} >> ${BASE_COLLECTION_PATH}/gather-debug.log 2>&1
find "${BASE_COLLECTION_PATH}" -empty -delete >> ${BASE_COLLECTION_PATH}/gather-debug.log 2>&1
exit 0
