#!/usr/bin/env bash
set -euo pipefail

if [[ "${1:-}" == "--" ]]; then
  shift
fi

if [[ "$#" -eq 0 ]]; then
  printf 'usage: dev-agent-worker -- <command> [args...]\n' >&2
  exit 2
fi

if [[ -z "${SPOON_AGENT_CONTAINER_RUNTIME:-}" ]]; then
  if command -v podman >/dev/null 2>&1; then
    export SPOON_AGENT_CONTAINER_RUNTIME=podman
  elif command -v docker >/dev/null 2>&1; then
    export SPOON_AGENT_CONTAINER_RUNTIME=docker
  else
    printf 'dev-agent-worker: podman or docker is required for container-backed jobs.\n' >&2
    exit 1
  fi
fi

export SPOON_AGENT_RUNTIME="${SPOON_AGENT_RUNTIME:-docker}"
export SPOON_AGENT_CONTAINER_ACCESS="${SPOON_AGENT_CONTAINER_ACCESS:-host_port}"
export SPOON_AGENT_WORKER_URL="${SPOON_AGENT_WORKER_URL:-http://localhost:${SPOON_AGENT_WORKER_HTTP_PORT:-3921}}"
export SPOON_AGENT_WORKER_INTERNAL_TOKEN="${SPOON_AGENT_WORKER_INTERNAL_TOKEN:-${SPOON_WORKER_TOKEN:-}}"
export SPOON_AGENT_WORKDIR="${SPOON_AGENT_LOCAL_WORKDIR:-.local/agent-work/${WITH_ENV_ENVIRONMENT:-dev}}"
export SPOON_AGENT_JOB_IMAGE="${SPOON_AGENT_LOCAL_JOB_IMAGE:-spoon-agent-job:latest}"
# Self-terminate if the dev runner dies, so the worker never orphans on port 3921.
export SPOON_AGENT_DEV_WATCHDOG="${SPOON_AGENT_DEV_WATCHDOG:-1}"

if [[ "$SPOON_AGENT_CONTAINER_ACCESS" == "host_port" && -z "${SPOON_AGENT_KEEP_NETWORK:-}" ]]; then
  unset SPOON_AGENT_NETWORK
fi

if ! "$SPOON_AGENT_CONTAINER_RUNTIME" image inspect "$SPOON_AGENT_JOB_IMAGE" >/dev/null 2>&1; then
  printf 'dev-agent-worker: job image %s is not present locally.\n' "$SPOON_AGENT_JOB_IMAGE" >&2
  printf 'Build it with: scripts/build-agent-images\n' >&2
fi

exec "$@"
