#!/bin/sh
set -eu

deadline=$(( $(date +%s) + ${TIMEOUT_SECONDS} ))

while true; do
  job_json=$(kubectl -n "${NAMESPACE}" get job "${JOB_NAME}" -o json)
  phase=$(printf '%s' "${job_json}" | node -e "let s='';process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>{const j=JSON.parse(s);const c=j.status?.conditions||[];const done=c.find(x=>x.type==='Complete'&&x.status==='True');const failed=c.find(x=>x.type==='Failed'&&x.status==='True');process.stdout.write(done?'complete':failed?'failed':'running');})")
  if [ "${phase}" = complete ]; then
    kubectl -n "${NAMESPACE}" logs "job/${JOB_NAME}" --all-containers --tail=240 2>/dev/null || true
    exit 0
  fi
  if [ "${phase}" = failed ]; then
    kubectl -n "${NAMESPACE}" logs "job/${JOB_NAME}" --all-containers --tail=240 2>/dev/null || true
    exit 1
  fi
  if [ "$(date +%s)" -ge "${deadline}" ]; then exit 124; fi
  sleep 2
done
