#!/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"

A_HANDLE="${1:-madhavajay}"
B_HANDLE="${2:-madhavajay-test}"
A_PORT="${A_PORT:-1420}"
B_PORT="${B_PORT:-1421}"

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 both instances"
  kill 0 2>/dev/null || true
}
trap cleanup EXIT INT TERM

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" 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" PORT="$B_PORT" \
  npx tauri dev --config "{\"build\":{\"devUrl\":\"http://localhost:$B_PORT\"}}" &

wait
