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

# Launch two separate Rho desktop instances, each bound to a different profile.
# Usage: ./dev-desktop-two.sh [handleA] [handleB]
#   defaults: madhavajay  madhavajay-test
# Each instance reads RHO_DESKTOP_IDENTITY as its default profile (see the
# launch_identity command), and runs on its own dev port so they don't collide.

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"
DESKTOP_DIR="$ROOT_DIR/desktop"
RELAY_DIR="$ROOT_DIR/relay"

A_HANDLE="${1:-madhavajay}"
B_HANDLE="${2:-madhavajay-test}"
A_PORT="${A_PORT:-1420}"
B_PORT="${B_PORT:-1421}"
RHO_START_RELAY="${RHO_START_RELAY:-1}"
RHO_RELAY_ADDR="${RHO_RELAY_ADDR:-127.0.0.1:8787}"
RHO_RELAY_URL="${RHO_RELAY_URL:-ws://$RHO_RELAY_ADDR}"
RHO_RELAY_HTTP_URL="${RHO_RELAY_HTTP_URL:-http://$RHO_RELAY_ADDR}"

to_identity() {
  case "$1" in
    rho://*) printf '%s' "$1" ;;
    *) printf 'rho://id/github/%s' "$1" ;;
  esac
}
A_ID="$(to_identity "$A_HANDLE")"
B_ID="$(to_identity "$B_HANDLE")"

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

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

cleanup() {
  log "stopping relay and both instances"
  kill 0 2>/dev/null || true
}
trap cleanup EXIT INT TERM

if [[ "$RHO_START_RELAY" == "1" ]]; then
  log "nostr relay: $RHO_RELAY_URL"
  cargo run --manifest-path "$RELAY_DIR/Cargo.toml" --features local \
    --bin rho-relay-local -- --addr "$RHO_RELAY_ADDR" &

  for _ in {1..40}; do
    if curl -fsS "$RHO_RELAY_HTTP_URL/health" >/dev/null 2>&1; then
      break
    fi
    sleep 0.25
  done

  if ! curl -fsS "$RHO_RELAY_HTTP_URL/health" >/dev/null 2>&1; then
    log "relay did not become healthy at $RHO_RELAY_HTTP_URL/health"
    exit 1
  fi
else
  log "using external nostr relay: $RHO_RELAY_URL"
fi

cd "$DESKTOP_DIR"
log "instance A: $A_HANDLE ($A_ID) on http://localhost:$A_PORT"
log "instance B: $B_HANDLE ($B_ID) on http://localhost:$B_PORT"

RHO_REPO_ROOT="$ROOT_DIR" RHO_DESKTOP_IDENTITY="$A_ID" \
  RHO_RELAY_URL="$RHO_RELAY_URL" RHO_RELAY_HTTP_URL="$RHO_RELAY_HTTP_URL" \
  PORT="$A_PORT" \
  npm run tauri:dev &

# Stagger so the shared cargo target lock is taken by A first.
sleep 4

RHO_REPO_ROOT="$ROOT_DIR" RHO_DESKTOP_IDENTITY="$B_ID" \
  RHO_RELAY_URL="$RHO_RELAY_URL" RHO_RELAY_HTTP_URL="$RHO_RELAY_HTTP_URL" \
  PORT="$B_PORT" \
  npx tauri dev --config "{\"build\":{\"devUrl\":\"http://localhost:$B_PORT\"}}" &

wait
