#!/bin/bash

SHORT="a:,l:,n:,j:,h"
LONG="apply:,logfile:,namespace:,job:,help"
OPTS=$(getopt -a -n create --options $SHORT --longoptions $LONG -- "$@")

eval set -- "$OPTS"

HERE=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

# Source shared helper scripts
. $HERE/helpers.sh

function usage() {
   echo "This is the Flux Cloud MiniCluster job runner, where we apply a custom resource definition (CRD)."
   echo "usage: minicluster-run --apply <crd> --logfile /path/to/log.out --namespace <namespace>"
}

NAMESPACE="flux-operator"

while :
do
  case "$1" in
    -l | --logfile)
        LOGFILE=$2
        shift 2
        ;;
    -a | --apply)
        CRD=$2
        shift 2
        ;;
    -n | --namespace)
        NAMESPACE=$2
        shift 2
        ;;
    -j | --job)
        JOB=$2
        shift 2
        ;;
    -h | --help)
      usage
      exit 2
      ;;
    --)
      shift;
      break
      ;;
    *)
      echo "Unexpected option: $1"
      ;;
  esac
done

# Required arguments
if [ -z ${CRD+x} ]; then
    echo "A custom resource definition is required with --apply";
    exit 1
fi

if [ -z ${JOB+x} ]; then
    echo "A job name is required with --job";
    exit 1
fi

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

is_installed kubectl

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

# Apply the job, get pods
run_echo kubectl apply -f ${CRD}
run_echo kubectl get -n ${NAMESPACE} pods

# continue until we find the index-0 pod
brokerPrefix="${JOB}-0"
brokerReady="false"

echo
print_blue "Waiting for broker pod with prefix ${brokerPrefix} to be created..."
while [[ "${brokerReady}" == "false" ]]; do
    echo -n "."
    sleep 2
    for pod in $(kubectl get pods --selector=job-name=${JOB} --namespace ${NAMESPACE} --output=jsonpath='{.items[*].metadata.name}'); do
        if [[ "${pod}" == ${brokerPrefix}* ]]; then
            echo
            print_green "🌀️ Broker pod is created."
            brokerReady="true"
            break
        fi
    done
done

# Now broker pod needs to be running
echo
print_blue "Waiting for broker pod with prefix ${brokerPrefix} to be running..."
brokerReady="false"
while [[ "${brokerReady}" == "false" ]]; do
    echo -n "."
    for pod in $(kubectl get pods --namespace ${NAMESPACE} --field-selector=status.phase=Running --output=jsonpath='{.items[*].metadata.name}'); do
        if [[ "${pod}" == ${brokerPrefix}* ]]; then
            echo
            print_green "🌀️ Broker pod is running."
            brokerReady="true"
            break
        fi
    done
done

# 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}" != "0" ]]; then
       echo "Container in ${JOB} had nonzero exit code"
    fi
done

run_echo kubectl delete -f ${CRD}
