#!/bin/bash
set -Eeuo pipefail

COZE_WORKSPACE_PATH="${COZE_WORKSPACE_PATH:-$(pwd)}"
PORT="${PORT:-<%= port %>}"
DEPLOY_RUN_PORT="${DEPLOY_RUN_PORT:-${PORT}}"
cd "${COZE_WORKSPACE_PATH}"

get_listening_pids() {
  local port="$1"

  if command -v lsof >/dev/null 2>&1; then
    lsof -tiTCP:"${port}" -sTCP:LISTEN 2>/dev/null || true
  elif command -v ss >/dev/null 2>&1; then
    ss -H -lntp 2>/dev/null \
      | awk -v port="${port}" '$4 ~ ":"port"$"' \
      | grep -o 'pid=[0-9]*' \
      | cut -d= -f2 \
      | sort -u || true
  else
    echo "Warning: neither lsof nor ss found, cannot check port ${port}." >&2
  fi
}

kill_port_if_listening() {
  local port="$1"
  local pids

  pids="$(get_listening_pids "${port}")"
  if [[ -z "${pids}" ]]; then
    echo "Port ${port} is free."
    return
  fi

  echo "Port ${port} is in use by PIDs: ${pids//$'\n'/ } (SIGKILL)"
  echo "${pids}" | xargs kill -9 2>/dev/null || true
  sleep 1

  pids="$(get_listening_pids "${port}")"
  if [[ -n "${pids}" ]]; then
    echo "Failed to clear port ${port}; remaining PIDs: ${pids//$'\n'/ }." >&2
    return 1
  fi

  echo "Port ${port} cleared."
}

echo "Clearing port ${DEPLOY_RUN_PORT} before start."
kill_port_if_listening "${DEPLOY_RUN_PORT}"

<% if (process.env.NODE_ENV === 'test') { %>
# Keep the process attached in tests so the test runner can collect logs and stop it.
exec env COZE_PHASER_GAME_ENV=PROD pnpm vite preview \
  --port "${DEPLOY_RUN_PORT}" \
  --host 127.0.0.1 \
  --strictPort
<% } else { %>
LOG_DIR="${COZE_WORKSPACE_PATH}/logs"
LOG_FILE="${LOG_DIR}/phaser-start.log"
PID_FILE="${LOG_DIR}/phaser-start.pid"
mkdir -p "${LOG_DIR}"

echo "Starting Phaser production server on port ${DEPLOY_RUN_PORT}..."
server_pid="$(COZE_PHASER_GAME_ENV=PROD node scripts/spawn-detached.cjs \
  "${LOG_FILE}" pnpm vite preview \
  --port "${DEPLOY_RUN_PORT}" \
  --host 127.0.0.1 \
  --strictPort)"
echo "${server_pid}" > "${PID_FILE}"

sleep 1
if ! kill -0 "${server_pid}" 2>/dev/null; then
  echo "Phaser production server failed to start. See ${LOG_FILE}." >&2
  tail -n 20 "${LOG_FILE}" >&2 || true
  rm -f "${PID_FILE}"
  exit 1
fi

echo "Phaser production server started (PID: ${server_pid})."
echo "Log file: ${LOG_FILE}"
echo "PID file: ${PID_FILE}"
<% } %>
