#!/bin/sh
set -eu

is_true() {
  normalized=$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')
  case "$normalized" in
    1|true|yes|on)
      return 0
      ;;
    *)
      return 1
      ;;
  esac
}

start_browser_debug_services() {
  display="${TENCENT_BROWSER_DISPLAY:-:99}"
  resolution="${TENCENT_BROWSER_VNC_RESOLUTION:-1600x900x24}"
  display_number="${display#:}"
  display_number="${display_number%%.*}"
  display_socket="/tmp/.X11-unix/X${display_number}"
  display_lock="/tmp/.X${display_number}-lock"

  if [ -S "$display_socket" ] && [ ! -f "$display_lock" ]; then
    rm -f "$display_socket"
  fi

  if [ -f "$display_lock" ]; then
    display_pid=$(cat "$display_lock" 2>/dev/null || true)
    if [ -z "$display_pid" ] || ! kill -0 "$display_pid" 2>/dev/null; then
      rm -f "$display_lock" "$display_socket"
    fi
  fi

  export DISPLAY="$display"
  Xvfb "$display" -screen 0 "$resolution" -nolisten tcp >/tmp/xvfb.log 2>&1 &
  xvfb_pid=$!

  ready=0
  attempt=0
  while [ "$attempt" -lt 50 ]; do
    if [ -S "$display_socket" ]; then
      ready=1
      break
    fi

    if ! kill -0 "$xvfb_pid" 2>/dev/null; then
      break
    fi

    attempt=$((attempt + 1))
    sleep 0.1
  done

  if [ "$ready" -ne 1 ]; then
    echo "[backend-dev] Xvfb display ${DISPLAY} not ready for x11vnc; skip noVNC startup" >&2
    return
  fi

  if ! is_true "${TENCENT_BROWSER_NOVNC_ENABLED:-true}"; then
    echo "[backend-dev] headed browser enabled on ${DISPLAY}; noVNC disabled"
    return
  fi

  vnc_port="${TENCENT_BROWSER_VNC_PORT:-5900}"
  novnc_port="${TENCENT_BROWSER_NOVNC_PORT:-6080}"

  x11vnc \
    -display "$display" \
    -rfbport "$vnc_port" \
    -forever \
    -shared \
    -nopw \
    -listen 0.0.0.0 \
    -xkb >/tmp/x11vnc.log 2>&1 &

  if command -v novnc_proxy >/dev/null 2>&1; then
    novnc_proxy --listen "$novnc_port" --vnc "127.0.0.1:${vnc_port}" >/tmp/novnc.log 2>&1 &
  elif [ -x /usr/share/novnc/utils/novnc_proxy ]; then
    /usr/share/novnc/utils/novnc_proxy --listen "$novnc_port" --vnc "127.0.0.1:${vnc_port}" >/tmp/novnc.log 2>&1 &
  elif command -v websockify >/dev/null 2>&1 && [ -d /usr/share/novnc ]; then
    websockify --web=/usr/share/novnc "$novnc_port" "127.0.0.1:${vnc_port}" >/tmp/novnc.log 2>&1 &
  else
    echo "[backend-dev] noVNC requested but novnc/websockify not found"
    return
  fi

  echo "[backend-dev] headed browser enabled on ${DISPLAY}; noVNC: http://127.0.0.1:${novnc_port}/vnc.html"
}

npm install --no-fund --no-audit

if ! is_true "${TENCENT_BROWSER_HEADLESS:-true}"; then
  start_browser_debug_services
fi

exec npm run dev
