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

readonly SSH_ALIAS="mission-gpu"
readonly LOCAL_PORT="${CVAT_LOCAL_PORT:-18080}"
readonly REMOTE_WSL_PORT="18080"
readonly LINUX_START_SCRIPT='/mnt/d/NDC_MISSIONCORE/workspace/mission-core-compute/cvat/start_cvat_runtime.sh'

if curl --max-time 2 --fail --silent \
  "http://localhost:${LOCAL_PORT}/api/server/about" >/dev/null 2>&1; then
  printf 'cvat_tunnel_ready url=http://localhost:%s\n' "${LOCAL_PORT}"
  exit 0
fi

if command -v lsof >/dev/null \
  && lsof -nP -iTCP:"${LOCAL_PORT}" -sTCP:LISTEN >/dev/null 2>&1; then
  echo "Local port ${LOCAL_PORT} is already occupied by a non-responsive process" >&2
  exit 2
fi

runtime_command="wsl.exe -d MissionCore-CVAT -u root -- bash ${LINUX_START_SCRIPT} --keepalive"
background=false
if [[ "${1:-}" == "--background" ]]; then
  background=true
  ssh -f "${SSH_ALIAS}" "${runtime_command}"
else
  ssh "${SSH_ALIAS}" "${runtime_command}" &
  runtime_ssh_pid=$!
  cleanup() {
    if [[ -n "${tunnel_ssh_pid:-}" ]]; then
      kill "${tunnel_ssh_pid}" 2>/dev/null || true
    fi
    kill "${runtime_ssh_pid}" 2>/dev/null || true
  }
  trap cleanup EXIT INT TERM
fi

for attempt in $(seq 1 30); do
  cvat_ip="$(
    ssh "${SSH_ALIAS}" \
      "wsl.exe -d MissionCore-CVAT -u root -- hostname -I" \
      | tr -d '\r' | awk '{print $1}'
  )"
  if [[ "${cvat_ip}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    break
  fi
  sleep 1
done
if [[ ! "${cvat_ip:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "MissionCore-CVAT did not return a valid WSL address" >&2
  if [[ "${background}" == false ]]; then
    kill "${runtime_ssh_pid}" 2>/dev/null || true
  fi
  exit 3
fi

forward=(
  -N
  -L "${LOCAL_PORT}:${cvat_ip}:${REMOTE_WSL_PORT}"
  -o ExitOnForwardFailure=yes
  "${SSH_ALIAS}"
)

if [[ "${background}" == true ]]; then
  ssh -f "${forward[@]}"
else
  ssh "${forward[@]}" &
  tunnel_ssh_pid=$!
fi

for attempt in $(seq 1 60); do
  if curl --max-time 2 --fail --silent \
    "http://localhost:${LOCAL_PORT}/api/server/about" >/dev/null 2>&1; then
    printf 'cvat_tunnel_ready url=http://localhost:%s wsl_ip=%s\n' \
      "${LOCAL_PORT}" "${cvat_ip}"
    if [[ "${background}" == true ]]; then
      exit 0
    fi
    wait "${tunnel_ssh_pid}"
    tunnel_status=$?
    kill "${runtime_ssh_pid}" 2>/dev/null || true
    exit "${tunnel_status}"
  fi
  sleep 2
done

echo "CVAT tunnel did not become ready within 120 seconds" >&2
if [[ "${background}" == false ]]; then
  kill "${tunnel_ssh_pid}" "${runtime_ssh_pid}" 2>/dev/null || true
fi
exit 4
