#!/bin/sh
set -eu

repo=${UNIDESK_TRAN_REPO_ROOT:-/root/unidesk}
if [ ! -f "$repo/scripts/cli.ts" ]; then
  self_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
  repo=$(CDPATH= cd -- "$self_dir/.." && pwd)
fi

tran_timeout_seconds() {
  raw=${UNIDESK_TRAN_RUNTIME_TIMEOUT_SECONDS:-}
  if [ -z "$raw" ] && [ -n "${UNIDESK_TRAN_RUNTIME_TIMEOUT_MS:-}" ]; then
    case "$UNIDESK_TRAN_RUNTIME_TIMEOUT_MS" in
      ''|*[!0-9]*) raw=60 ;;
      *) raw=$(((${UNIDESK_TRAN_RUNTIME_TIMEOUT_MS} + 999) / 1000)) ;;
    esac
  fi
  if [ -z "$raw" ] && [ -n "${UNIDESK_SSH_RUNTIME_TIMEOUT_MS:-}" ]; then
    case "$UNIDESK_SSH_RUNTIME_TIMEOUT_MS" in
      ''|*[!0-9]*) raw=60 ;;
      *) raw=$(((${UNIDESK_SSH_RUNTIME_TIMEOUT_MS} + 999) / 1000)) ;;
    esac
  fi
  raw=${raw:-60}
  case "${raw:-60}" in
    ''|*[!0-9]*) raw=60 ;;
  esac
  [ "$raw" -gt 0 ] || raw=60
  [ "$raw" -le 60 ] || raw=60
  printf '%s\n' "$raw"
}

if [ "${UNIDESK_TRAN_TIMEOUT_GUARD:-0}" != "1" ] && command -v timeout >/dev/null 2>&1; then
  timeout_seconds=$(tran_timeout_seconds)
  set +e
  UNIDESK_TRAN_TIMEOUT_GUARD=1 timeout -s TERM -k 2s "${timeout_seconds}s" "$0" "$@"
  rc=$?
  set -e
  if [ "$rc" = 124 ] || [ "$rc" = 137 ] || [ "$rc" = 143 ]; then
    printf 'UNIDESK_TRAN_TIMEOUT_HINT {"code":"tran-top-level-timeout","level":"warning","timeoutSeconds":%s,"message":"tran exceeded the top-level runtime limit and was disconnected.","action":"Use short query plus poll semantics; do not keep tran open waiting for long CI/CD, trace, logs, or build progress."}\n' "$timeout_seconds" >&2
  fi
  exit "$rc"
fi

host=${UNIDESK_MAIN_SERVER_IP:-${UNIDESK_MAIN_SERVER_HOST:-${CODE_QUEUE_DEV_CONTAINER_MASTER_HOST:-}}}
runner_env=0
if [ -n "${CODE_QUEUE_SERVICE_ROLE:-}" ] || [ -n "${CODE_QUEUE_INSTANCE_ID:-}" ] || [ -n "${KUBERNETES_SERVICE_HOST:-}" ]; then
  runner_env=1
fi

if [ "$runner_env" = 1 ] && [ -n "$host" ] && [ "${UNIDESK_TRAN_LOCAL:-}" != "1" ]; then
  bun "$repo/scripts/cli.ts" --main-server-ip "$host" ssh "$@"
  exit $?
fi

bun "$repo/scripts/cli.ts" ssh "$@"
