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

: "${TS_AUTHKEY:?TS_AUTHKEY is required}"

mkdir -p /var/lib/tailscale /var/run/tailscale

# Start tailscaled in userspace mode for container environments without /dev/net/tun.
tailscaled \
  --state=/var/lib/tailscale/tailscaled.state \
  --socket=/var/run/tailscale/tailscaled.sock \
  --tun=userspace-networking &

# Wait for tailscaled socket readiness to reduce startup race conditions.
for i in {1..30}; do
  if tailscale --socket=/var/run/tailscale/tailscaled.sock status >/dev/null 2>&1; then
    break
  fi
  sleep 1
done

tailscale --socket=/var/run/tailscale/tailscaled.sock up \
  --authkey="${TS_AUTHKEY}" \
  --hostname="${TS_HOSTNAME:-vast-lc0}" \
  --accept-dns="${TS_ACCEPT_DNS:-false}"

if [[ "${ENABLE_TS_SERVE:-1}" == "1" ]]; then
  tailscale --socket=/var/run/tailscale/tailscaled.sock serve tcp 5555 tcp://127.0.0.1:5555

  if [[ -n "${UCI_ENGINE_PROFILES:-}" ]] && [[ -f "${UCI_ENGINE_PROFILES}" ]]; then
    while read -r port; do
      [[ -z "${port}" ]] && continue
      [[ "${port}" == "5555" ]] && continue
      tailscale --socket=/var/run/tailscale/tailscaled.sock serve tcp "${port}" "tcp://127.0.0.1:${port}"
    done < <(awk '/^[[:space:]]*#/ {next} NF >= 2 {print $2}' "${UCI_ENGINE_PROFILES}" | sort -u)
  fi

  if [[ "${ENABLE_MGMT:-1}" == "1" ]] && [[ "${ENABLE_TS_SERVE_MGMT:-1}" == "1" ]]; then
    tailscale --socket=/var/run/tailscale/tailscaled.sock serve tcp 53350 tcp://127.0.0.1:53350
  fi
  LISTEN_ADDR="127.0.0.1:5555"
else
  LISTEN_ADDR="0.0.0.0:5555"
fi

MGMT_LISTEN_VALUE="${UCI_MGMT_LISTEN:-127.0.0.1:53350}"
if [[ "${ENABLE_MGMT:-1}" != "1" ]]; then
  MGMT_LISTEN_VALUE=""
fi

exec /usr/local/bin/uci-bridge \
  --listen "${LISTEN_ADDR}" \
  --profiles "${UCI_ENGINE_PROFILES:-}" \
  --mgmt-listen "${MGMT_LISTEN_VALUE}" \
  --mgmt-advertise-host "${MGMT_ADVERTISE_HOST:-${TS_HOSTNAME:-}}" \
  --rewrite-id-name "${UCI_REWRITE_ID_NAME:-0}" \
  --id-name-separator "${UCI_ID_NAME_SEPARATOR:-##}" \
  --engine-name "${UCI_ENGINE_NAME:-lc0-cloud}" \
  --lc0 "${LC0_PATH:-/usr/local/bin/lc0}" \
  --weights "${LC0_WEIGHTS:-/data/weights.pb.gz}" \
  --backend "${LC0_BACKEND:-cuda-fp16}" \
  --backend-opts "${LC0_BACKEND_OPTS:-}" \
  --threads "${LC0_THREADS:-2}" \
  --nncache "${LC0_NNCACHE:-200000}" \
  --minibatch-size "${LC0_MINIBATCH_SIZE:-0}" \
  --max-prefetch "${LC0_MAX_PREFETCH:-32}" \
  --engine-idle-timeout "${LC0_ENGINE_IDLE_TIMEOUT:-1h}" \
  --idle-exit-timeout "${UCI_IDLE_EXIT_TIMEOUT:-0}" \
  --auth-token-env "${UCI_AUTH_TOKEN_ENV:-UCI_AUTH_TOKEN}"
