#!/bin/sh
# The runner for one job. A Hanzo Git job arrives as a registration token; a GitHub
# job arrives as a just-in-time configuration. Either way the process ends with
# the job, and the pod with it.
set -eu
if [ -n "${RUNNER_JITCONFIG:-}" ]; then
  cd /opt/actions-runner
  # The configuration was minted FOR one already-queued job, so a runner that
  # has claimed nothing after ten minutes is waiting for a job that is gone --
  # cancelled, or finished by a runner that answered first. ./run.sh has no
  # timeout for that: it prints "Listening for Jobs" and stays until the Job's
  # four-hour deadline, holding one of the six runner slots the whole cluster
  # has. Two were doing exactly that, for 151 and 73 minutes, while the queue
  # behind them was refused with "too many concurrent runners".
  #
  # Claiming a job is visible without parsing logs: the listener forks
  # Runner.Worker to run it, and that process lives as long as the job does.
  ./run.sh --jitconfig "$RUNNER_JITCONFIG" &
  listener=$!
  ( sleep 600
    pgrep -f Runner.Worker >/dev/null 2>&1 || kill "$listener" 2>/dev/null
  ) &
  wait "$listener"
  exit
fi
: "${GIT_RUNNER_URL:?the Hanzo Git URL}" "${GIT_RUNNER_TOKEN:?a registration token}" "${RUNNER_LABELS:?the labels the job asked for}"
git-runner register --no-interactive --ephemeral \
  --instance "$GIT_RUNNER_URL" --token "$GIT_RUNNER_TOKEN" \
  --name "${RUNNER_NAME:-$(hostname)}" --labels "$RUNNER_LABELS"
exec git-runner daemon --once
