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

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
DESKTOP_DIR="$ROOT_DIR/desktop"
PORT="${PORT:-1420}"
KILL_PORTS="${KILL_PORTS:-1}"
KILL_ALL_DESKTOP="${KILL_ALL_DESKTOP:-0}"

log() {
  printf '[rho] %s\n' "$*"
}

kill_port() {
  local port="$1"
  if [[ "$KILL_PORTS" != "1" ]]; then
    return 0
  fi
  if ! command -v lsof >/dev/null 2>&1; then
    return 0
  fi
  local pids
  pids="$(lsof -ti tcp:"$port" 2>/dev/null || true)"
  if [[ -n "$pids" ]]; then
    log "stopping processes on port $port"
    # shellcheck disable=SC2086
    kill $pids 2>/dev/null || true
  fi
}

cleanup() {
  kill_port "$PORT"
}

if [[ "$KILL_ALL_DESKTOP" == "1" ]]; then
  pkill -f "rho-desktop|Rho.app" 2>/dev/null || true
fi

trap cleanup EXIT
kill_port "$PORT"

if [[ ! -d "$DESKTOP_DIR/node_modules" ]]; then
  log "installing desktop npm dependencies"
  (cd "$DESKTOP_DIR" && npm install)
fi

export PORT
export RHO_REPO_ROOT="$ROOT_DIR"

log "starting Rho desktop on http://localhost:$PORT"
cd "$DESKTOP_DIR"
exec npm run tauri:dev
