#!/bin/bash

# This is a template that will be populated with variables by Flux-Cloud
# It used to be a script proper with getopt, but in practice this was
# erroneous on different operating systems.

# Include shared helper scripts
{% include "helpers.sh" %}

NAMESPACE="{% if minicluster.namespace %}{{ minicluster.namespace }}{% else %}flux-operator{% endif %}"
CRD="{{ crd }}"
JOB="{{ minicluster.name }}"
LOGFILE="{{ logfile }}"

print_magenta "  apply : ${CRD}"
print_magenta "    job : ${JOB}"
print_magenta "logfile : ${LOGFILE}"

is_installed kubectl

# Ensure we wait for the space to be cleaned up
{% include "wait_for_cleanup.sh" %}

# Create the namespace (ok if already exists)
run_echo_allow_fail kubectl create namespace ${NAMESPACE}

{% include "wait_for_broker.sh" %}

# Get the name of the pods
pods=($(kubectl get pods --selector=job-name=${JOB} --namespace ${NAMESPACE} --output=jsonpath='{.items[*].metadata.name}'))
brokerpod=${pods[0]}

# This will hang like this until the job finishes running
echo
print_green "kubectl -n ${NAMESPACE} logs ${brokerpod} -f > ${LOGFILE}"
kubectl -n ${NAMESPACE} logs ${brokerpod} -f > ${LOGFILE}

for exitcode in $(kubectl get -n ${NAMESPACE} pod --selector=job-name=${JOB} --output=jsonpath={.items...containerStatuses..state.terminated.exitCode}); do
    if [[ ${exitcode} -ne 0 ]]; then
       echo "Container in ${JOB} had nonzero exit code"
    fi
done

run_echo kubectl delete -f ${CRD}
