#!/bin/bash
set -eu
REPO=$1
OUT=$2
ELECTRON=$3
mkdir -p "$OUT"
export XDG_DATA_HOME="$OUT/data" XDG_CONFIG_HOME="$OUT/config" XDG_CACHE_HOME="$OUT/cache" XDG_RUNTIME_DIR="$OUT/runtime"
mkdir -p "$XDG_RUNTIME_DIR" "$XDG_DATA_HOME/gnome-shell/extensions/snap-shot@t3.codes"
chmod 700 "$XDG_RUNTIME_DIR"
cp -r "$REPO/apps/desktop/gnome-extension/." "$XDG_DATA_HOME/gnome-shell/extensions/snap-shot@t3.codes/"
export XDG_CURRENT_DESKTOP=GNOME XDG_SESSION_TYPE=wayland WAYLAND_DISPLAY=wayland-proof
export LIBGL_ALWAYS_SOFTWARE=1 NO_AT_BRIDGE=1 MUTTER_DEBUG_DUMMY_MODE_SPECS=1440x900
export T3CODE_HOME="$OUT/t3-home" T3CODE_DEV_SEED=0
# All services inherit the isolated desktop session.
dbus-update-activation-environment XDG_DATA_HOME XDG_CONFIG_HOME XDG_CACHE_HOME XDG_RUNTIME_DIR XDG_CURRENT_DESKTOP XDG_SESSION_TYPE WAYLAND_DISPLAY DISPLAY
pipewire > "$OUT/pipewire.log" 2>&1 & PIPEWIRE_PID=$!
gnome-shell --nested --wayland --wayland-display=wayland-proof > "$OUT/gnome.log" 2>&1 & SHELL_PID=$!
for attempt in $(seq 1 30); do
 if gdbus call --session --dest org.gnome.Shell --object-path /org/gnome/Shell --method org.gnome.Shell.Extensions.EnableExtension snap-shot@t3.codes > "$OUT/extension-enable.txt" 2>&1; then break; fi
 sleep 1
done
/usr/libexec/xdg-desktop-portal-gnome > "$OUT/portal-gnome.log" 2>&1 & BACKEND_PID=$!
/usr/libexec/xdg-desktop-portal > "$OUT/portal.log" 2>&1 & PORTAL_PID=$!
env > "$OUT/session.env"
cd "$REPO/apps/desktop"
"$ELECTRON" --no-sandbox --disable-gpu --ozone-platform=wayland --remote-debugging-port=19321 dist-electron/main.cjs > "$OUT/app.log" 2>&1 & APP_PID=$!
printf '%s\n' "$APP_PID" "$PORTAL_PID" "$BACKEND_PID" "$SHELL_PID" "$PIPEWIRE_PID" > "$OUT/pids"
trap 'kill "$APP_PID" "$PORTAL_PID" "$BACKEND_PID" "$SHELL_PID" "$PIPEWIRE_PID" 2>/dev/null || true' EXIT
while [ ! -f "$OUT/stop" ]; do sleep 1; done
