#!/usr/bin/env bash
set -u
BIN="$HOME/.local/bin"
BRAID_HOME="${BRAID_HOME:-$HOME/.braid}"
mkdir -p "$BRAID_HOME"

# Always open the UI first. This makes double-click visibly useful even before pairing.
nohup "$BIN/braid-visualizer" >"$BRAID_HOME/visualizer-launch.log" 2>&1 </dev/null &

# Launch receiver in a persistent terminal. Avoid Desktop Entry Terminal=true because
# some GNOME sessions close the transient terminal immediately when setup is incomplete.
CMD="$BIN/braid-receiver"
if command -v kgx >/dev/null 2>&1; then
  exec kgx -- bash -lc "$CMD; rc=\$?; if [ \$rc -ne 0 ]; then echo; echo 'Braid receiver exited with status' \$rc; read -r -p 'Press Enter to close...' _; fi"
elif command -v gnome-terminal >/dev/null 2>&1; then
  exec gnome-terminal -- bash -lc "$CMD; rc=\$?; if [ \$rc -ne 0 ]; then echo; echo 'Braid receiver exited with status' \$rc; read -r -p 'Press Enter to close...' _; fi"
elif command -v x-terminal-emulator >/dev/null 2>&1; then
  exec x-terminal-emulator -e bash -lc "$CMD; rc=\$?; if [ \$rc -ne 0 ]; then echo; read -r -p 'Press Enter to close...' _; fi"
elif command -v konsole >/dev/null 2>&1; then
  exec konsole -e bash -lc "$CMD; rc=\$?; if [ \$rc -ne 0 ]; then echo; read -r -p 'Press Enter to close...' _; fi"
else
  # Last-resort: log receiver output rather than failing silently.
  nohup "$CMD" >"$BRAID_HOME/receiver-launch.log" 2>&1 </dev/null &
  exit 0
fi
