#!/bin/zsh
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$REPO_ROOT"

export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"

for node_bin in "$HOME"/.nvm/versions/node/*/bin; do
  if [ -d "$node_bin" ]; then
    export PATH="$node_bin:$PATH"
  fi
done

export NEXT_PUBLIC_API_BASE_URL="${NEXT_PUBLIC_API_BASE_URL:-http://127.0.0.1:8000}"
export NEXT_PUBLIC_WS_BASE_URL="${NEXT_PUBLIC_WS_BASE_URL:-ws://127.0.0.1:8000}"

WEB_HOST="${WEB_HOST:-0.0.0.0}"
WEB_PORT="${WEB_PORT:-3000}"

wait_for_port_release() {
  local pid="$1"
  local attempts=0

  while lsof -nP -iTCP:"$WEB_PORT" -sTCP:LISTEN -t 2>/dev/null | grep -qx "$pid"; do
    if [ "$attempts" -ge 10 ]; then
      kill -KILL "$pid" 2>/dev/null || true
      break
    fi
    sleep 1
    attempts=$((attempts + 1))
  done
}

for pid in $(lsof -nP -iTCP:"$WEB_PORT" -sTCP:LISTEN -t 2>/dev/null || true); do
  if [ "$pid" = "$$" ]; then
    continue
  fi

  owner="$(ps -o user= -p "$pid" | tr -d ' ')"
  if [ -z "$owner" ] || [ "$owner" != "$USER" ]; then
    echo "Refusing to stop process $pid on port $WEB_PORT because it is not owned by $USER." >&2
    exit 1
  fi

  echo "Stopping stale process $pid on port $WEB_PORT." >&2
  kill -TERM "$pid" 2>/dev/null || true
  wait_for_port_release "$pid"
done

exec caffeinate -i -m -s npm --workspace apps/web run start -- --hostname "$WEB_HOST" --port "$WEB_PORT"
