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

DISPLAY="${DISPLAY:-:99}"
ARCHIVE_WORKER_VIEWPORT="${ARCHIVE_WORKER_VIEWPORT:-1366x768x24}"
ARCHIVE_WORKER_VNC_PORT="${ARCHIVE_WORKER_VNC_PORT:-5900}"
export DISPLAY

xvfb_pid=""
vnc_pid=""
child_pid=""

cleanup() {
  local status=$?
  if [[ -n "${child_pid}" ]] && kill -0 "${child_pid}" 2>/dev/null; then
    kill "${child_pid}" 2>/dev/null || true
  fi
  if [[ -n "${vnc_pid}" ]] && kill -0 "${vnc_pid}" 2>/dev/null; then
    kill "${vnc_pid}" 2>/dev/null || true
  fi
  if [[ -n "${xvfb_pid}" ]] && kill -0 "${xvfb_pid}" 2>/dev/null; then
    kill "${xvfb_pid}" 2>/dev/null || true
  fi
  exit "${status}"
}

trap cleanup EXIT INT TERM

if [[ "${ARCHIVE_WORKER_XVFB:-1}" != "0" ]]; then
  rm -f "/tmp/.X${DISPLAY#:}-lock"
  Xvfb "${DISPLAY}" -screen 0 "${ARCHIVE_WORKER_VIEWPORT}" -nolisten tcp >/tmp/archive-worker-xvfb.log 2>&1 &
  xvfb_pid=$!
  sleep "${ARCHIVE_WORKER_XVFB_DELAY:-0.5}"
fi

if [[ "${ARCHIVE_WORKER_VNC:-0}" == "1" ]]; then
  x11vnc \
    -display "${DISPLAY}" \
    -nopw \
    -forever \
    -shared \
    -rfbport "${ARCHIVE_WORKER_VNC_PORT}" \
    >/tmp/archive-worker-x11vnc.log 2>&1 &
  vnc_pid=$!
fi

if [[ "$#" -eq 0 ]]; then
  set -- help
fi

case "$1" in
  archive|help)
    set -- node src/cli.mjs "$@"
    ;;
  serve-worker)
    shift
    set -- node src/worker-server.mjs "$@"
    ;;
esac

"$@" &
child_pid=$!
wait "${child_pid}"
