#!/usr/bin/env bash
# Starts the v2 control-api if it is not already serving. Observability must never
# block a run, so every failure here is reported and ignored.
set -uo pipefail

V2_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
HOME_DIR="${V2_HARNESS_HOME:-${HARNESS_HOME:-${HOME}/.harness}}"
PORT_FILE="${HOME_DIR}/control-api.port"
TOKEN_FILE="${HOME_DIR}/token"
UNIT="v2-control-api"
VERSION="${V2_CONTROL_API_VERSION:-}"
if [[ -z "$VERSION" && -s "${V2_ROOT}/../ENGINE_VERSION" ]]; then
  VERSION="$(tr -d '[:space:]' <"${V2_ROOT}/../ENGINE_VERSION")"
fi
VERSION="${VERSION:-dev}"

serving() {
  local port token health
  [[ -s "$PORT_FILE" && -s "$TOKEN_FILE" ]] || return 1
  port="$(cat "$PORT_FILE")"
  token="$(cat "$TOKEN_FILE")"
  health="$(curl -fsS -m 2 -H "authorization: Bearer ${token}" "http://127.0.0.1:${port}/health" 2>/dev/null)" || return 1
  [[ "$health" == *"\"version\":\"${VERSION}\""* && "$health" == *'"events":true'* && "$health" == *'/runs/:id/events'* ]]
}

if [[ "${V2_CONTROL_API:-on}" == off ]]; then
  exit 0
fi

# A transient unit keeps the ExecStart it was created with, so an observer armed by an
# older engine bundle keeps serving after an upgrade and reports through last release's
# code. Only this bundle's control-api counts as already serving.
current_exec() {
  systemctl --user show "${UNIT}.service" -p ExecStart --value 2>/dev/null
}

replaced=0
case "$(current_exec)" in
  *"${V2_ROOT}/bin/control-api.js"*) ;;
  '') ;;
  *) systemctl --user stop "${UNIT}.service" >/dev/null 2>&1; replaced=1 ;;
esac

if [[ "$replaced" == 0 ]] && serving; then
  exit 0
fi

# A transient service, not a scope: systemd-run runs a scope in the calling
# process, which would hold the run in the foreground forever.
systemctl --user reset-failed "${UNIT}.service" >/dev/null 2>&1
if ! systemd-run --user --quiet --unit="$UNIT" \
  --setenv=V2_HARNESS_HOME="$HOME_DIR" \
  --setenv=V2_CONTROL_API_VERSION="$VERSION" \
  -- node "${V2_ROOT}/bin/control-api.js" >/dev/null 2>&1; then
  echo "runplan: could not start the v2 control-api — the run continues unobserved" >&2
  [[ "${V2_CONTROL_API_STRICT:-0}" == 1 ]] && exit 1
  exit 0
fi

for _ in $(seq 80); do
  if serving; then
    echo "runplan: v2 control-api on http://127.0.0.1:$(cat "$PORT_FILE")" >&2
    exit 0
  fi
  sleep 0.25
done

echo "runplan: the v2 control-api did not come up within 20s — the run continues unobserved" >&2
[[ "${V2_CONTROL_API_STRICT:-0}" == 1 ]] && exit 1
