#!/bin/sh
# nested-plasma.sh — sesión Plasma COMPLETA (kwin_wayland + plasmashell) como ventana dentro del
# compositor mirada vivo. kwin nesta en Xwayland :0 (backend X11, más estable que wayland-nested) y
# compone por SOFTWARE (llvmpipe/swrast) — el backend GL-hardware anidado segfaultea (gbm/renderD128).
# Cliente, no DRM master ⇒ seguro. plasmashell corre contra el socket propio de kwin (wl-kwin).
#   SECS=600 scripts/kde/nested-plasma.sh
set -u
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"; cd "$ROOT"
R="${RFS:-$ROOT/work/kde-rootfs}"; A="$ROOT/.dev-fs/alpine"
SECS="${SECS:-600}"; W="${W:-1600}"; H="${H:-900}"; XDISP="${XDISP:-:0}"
exec bwrap --overlay-src "$A" --overlay-src "$R" --tmp-overlay / \
  --dev-bind /dev /dev --proc /proc --bind /sys /sys --tmpfs /tmp --tmpfs /run \
  --bind /tmp/.X11-unix /tmp/.X11-unix --uid 0 --gid 0 \
  --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/user/0 \
  --setenv XDG_CONFIG_HOME /root/.config --setenv XDG_CACHE_HOME /root/.cache --setenv HOME /root \
  --setenv LIBGL_ALWAYS_SOFTWARE 1 --setenv GALLIUM_DRIVER llvmpipe \
  --setenv MESA_LOADER_DRIVER_OVERRIDE swrast --setenv LIBGL_DRIVERS_PATH /usr/lib/dri \
  --setenv QT_QPA_FONTDIR /usr/share/fonts/dejavu --setenv SHELL /bin/sh \
  --setenv QT_QUICK_BACKEND software \
  --setenv DISPLAY "$XDISP" \
  sh -c '
    mkdir -p /run/user/0 /run/dbus /root/.config /root/.cache /etc; chmod 700 /run/user/0
    cat /proc/sys/kernel/random/uuid | tr -d - > /etc/machine-id
    export DBUS_SESSION_BUS_ADDRESS=$(dbus-daemon --session --fork --print-address 2>/dev/null)
    echo "dbus=${DBUS_SESSION_BUS_ADDRESS:-VACIO}  DISPLAY='"$XDISP"'"
    echo "-- kwin_wayland (X11 nested, sw-GL, '"$W"'x'"$H"')…"
    kwin_wayland --x11-display '"$XDISP"' --socket wl-kwin --width '"$W"' --height '"$H"' --xwayland >/tmp/kwin.log 2>&1 &
    KWIN=$!
    for i in $(seq 1 50); do [ -S /run/user/0/wl-kwin ] && break
      kill -0 $KWIN 2>/dev/null || { echo "   !! kwin murió:"; tail -15 /tmp/kwin.log; exit 1; }; sleep 0.5; done
    [ -S /run/user/0/wl-kwin ] && echo "   compositor OK (wl-kwin) — ventana kwin en tu pantalla" || { echo "   !! sin socket"; tail -15 /tmp/kwin.log; exit 1; }
    export WAYLAND_DISPLAY=wl-kwin; unset DISPLAY
    KAMD=$(ls /usr/lib*/libexec/kactivitymanagerd 2>/dev/null | head -1)
    [ -n "$KAMD" ] && { "$KAMD" >/tmp/kamd.log 2>&1 & sleep 2; }
    echo "-- plasmashell…"; plasmashell >/tmp/plasmashell.log 2>&1 &
    sleep 12
    echo "== procesos =="; ps axo comm 2>/dev/null | grep -E "kwin|plasma|kactiv" | sort -u | tr "\n" " "; echo
    echo "== plasmashell.log =="; tail -14 /tmp/plasmashell.log
    wait $KWIN
  '
