#!/usr/bin/env bash
# run-plasma-headless.sh — levanta la sesión Plasma HEADLESS con render por SOFTWARE (mesa-swrast/swrast)
# dentro del rootfs musl soberano, vía BWRAP (rootfs merged como / — imprescindible: el hack
# loader --library-path rompe el dlopen de plugins de kwin ⇒ QPA create() core-dumpea).
#
# ✅ VALIDADO: kwin_wayland --virtual levanta el compositor (socket wayland-0) y plasmashell CONECTA.
#    Bloqueo actual = falta el shell org.kde.plasma.desktop (paquete `plasma-desktop`, no construido).
#
# Requiere (en el worker, host glibc): work/kde-store-rootfs hidratado + complete-closure + mesa-swrast
# hidratado (swap iris→swrast). Correr: scripts/kde/run-plasma-headless.sh
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"; cd "$ROOT"
R="${RFS:-$ROOT/work/kde-store-rootfs}"; A="$ROOT/.dev-fs/alpine"
SECS="${SECS:-30}"; CLIENT="${CLIENT:-plasmashell}"   # CLIENT=/usr/bin/foo para probar otro cliente wayland

exec bwrap --overlay-src "$A" --overlay-src "$R" --tmp-overlay / \
  --dev-bind /dev /dev --proc /proc --bind /sys /sys --tmpfs /tmp --tmpfs /run \
  --setenv PATH /usr/bin:/bin:/usr/sbin:/sbin \
  --setenv LD_LIBRARY_PATH /usr/lib64:/usr/lib/qt6:/usr/lib:/lib \
  --setenv QT_PLUGIN_PATH /usr/lib64/qt6/plugins:/usr/lib/qt6/plugins \
  --setenv QML2_IMPORT_PATH /usr/lib64/qt6/qml:/usr/lib/qt6/qml \
  --setenv QML_IMPORT_PATH /usr/lib64/qt6/qml:/usr/lib/qt6/qml \
  --setenv XDG_DATA_DIRS /usr/share --setenv XDG_RUNTIME_DIR /run \
  --setenv XDG_CONFIG_HOME /run/cfg --setenv HOME /run \
  --setenv LIBGL_ALWAYS_SOFTWARE 1 --setenv GALLIUM_DRIVER swrast \
  --setenv LIBGL_DRIVERS_PATH /usr/lib/dri --setenv MESA_LOADER_DRIVER_OVERRIDE swrast \
  --setenv QT_QUICK_BACKEND software \
  sh -c '
    set -e
    mkdir -p /run/cfg /run/dbus
    export DBUS_SESSION_BUS_ADDRESS=$(dbus-daemon --session --fork --print-address 2>/dev/null)
    echo "dbus=$DBUS_SESSION_BUS_ADDRESS"
    /usr/bin/kwin_wayland --virtual --width 1280 --height 800 >/tmp/kwin.log 2>&1 &
    for i in $(seq 1 30); do [ -S /run/wayland-0 ] && break; sleep 0.5; done
    [ -S /run/wayland-0 ] && echo "compositor OK (wayland-0)" || { echo "kwin NO arrancó"; tail /tmp/kwin.log; exit 1; }
    export WAYLAND_DISPLAY=wayland-0
    # kactivitymanagerd: plasmashell ABORTA si no corre. Lo lanzamos (registra su servicio D-Bus).
    KAMD=$(ls /usr/lib*/libexec/kactivitymanagerd 2>/dev/null | head -1)
    [ -n "$KAMD" ] && { "$KAMD" >/tmp/kamd.log 2>&1 & sleep 3; echo "kactivitymanagerd lanzado"; }
    '"$CLIENT"' >/tmp/client.log 2>&1 &
    sleep '"$SECS"'
    echo "=== kwin.log (tail) ==="; tail -15 /tmp/kwin.log
    echo "=== '"$CLIENT"'.log (tail) ==="; tail -25 /tmp/client.log
    echo "=== procesos ==="; ps axo comm 2>/dev/null | grep -E "kwin|plasma" | sort -u
    pkill -f kwin_wayland 2>/dev/null || true
  '
