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

export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

readonly FREE_GIB_FLOOR="${FREE_GIB_FLOOR:-360}"
readonly WINDOWS_ROOT="/mnt/d/NDC_MISSIONCORE"
readonly COMPUTE_ROOT="${WINDOWS_ROOT}/workspace/mission-core-compute"
readonly CVAT_ROOT="${WINDOWS_ROOT}/runtime/annotation/cvat/source/cvat-v2.70.0"
readonly OVERRIDE_FILE="${COMPUTE_ROOT}/cvat/docker-compose.override.yml"

if [[ "${EUID}" -ne 0 ]]; then
  echo "start_cvat_runtime.sh must run as root" >&2
  exit 2
fi

free_gib="$(df -BG --output=avail "${WINDOWS_ROOT}" | tail -n 1 | tr -dc '0-9')"
printf 'disk_guard stage=start free_gib=%s floor_gib=%s\n' \
  "${free_gib}" "${FREE_GIB_FLOOR}"
if (( free_gib < FREE_GIB_FLOOR )); then
  echo "D: free-space floor crossed; refusing to start CVAT" >&2
  exit 3
fi

test -f "${CVAT_ROOT}/docker-compose.yml"
test -f "${OVERRIDE_FILE}"
systemctl start docker

export CVAT_VERSION="v2.70.0"
export CVAT_HOST="localhost"
export CVAT_HTTP_PORT="8080"
export COMPOSE_PROJECT_NAME="missioncore-cvat"

compose=(
  docker compose
  --project-directory "${CVAT_ROOT}"
  -f "${CVAT_ROOT}/docker-compose.yml"
  -f "${OVERRIDE_FILE}"
)
"${compose[@]}" up -d --no-build

deadline=$((SECONDS + 180))
while true; do
  about_http="$(
    curl --silent --output /dev/null --write-out '%{http_code}' \
      http://localhost:8080/api/server/about || true
  )"
  tasks_http="$(
    curl --silent --output /dev/null --write-out '%{http_code}' \
      http://localhost:8080/api/tasks || true
  )"
  if [[ "${about_http}" == "200" ]] \
    && [[ "${tasks_http}" == "200" || "${tasks_http}" == "401" || "${tasks_http}" == "403" ]]; then
    break
  fi
  if (( SECONDS >= deadline )); then
    "${compose[@]}" ps
    echo "CVAT did not become ready within 180 seconds" >&2
    exit 4
  fi
  sleep 2
done

printf 'cvat_ready about_http=%s tasks_http=%s free_gib=%s\n' \
  "${about_http}" "${tasks_http}" "${free_gib}"

if [[ "${1:-}" == "--keepalive" ]]; then
  exec sleep infinity
fi
