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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/../../../../" && pwd)"

COMPOSE_FILE="${ROOT_DIR}/src/mvp/v1/docker-compose.yaml"

HEAD_CONTAINER="mvp-ray-head"
WORKER0_CONTAINER="mvp-ray-worker-0"
WORKER1_CONTAINER="mvp-ray-worker-1"

dc() {
  docker compose --project-directory "${ROOT_DIR}" -f "${COMPOSE_FILE}" "$@"
}

require_cmd() {
  local cmd="$1"
  command -v "${cmd}" >/dev/null 2>&1 || {
    echo "missing required command: ${cmd}" >&2
    exit 1
  }
}

ensure_container_running() {
  local name="$1"
  if ! docker ps --format '{{.Names}}' | grep -qx "${name}"; then
    echo "container not running: ${name}" >&2
    exit 1
  fi
}

dexec() {
  local name="$1"
  shift
  ensure_container_running "${name}"
  docker exec -i "${name}" "$@"
}

container_ip() {
  local name="$1"
  ensure_container_running "${name}"
  docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${name}"
}

timestamp() {
  date +"%Y%m%d_%H%M%S"
}
