#!/bin/bash
# Run Plasma Mobile inside a nested KWin Wayland session.
set -u

export XDG_SESSION_TYPE=wayland
export XDG_SESSION_DESKTOP=KDE
export XDG_CURRENT_DESKTOP=KDE
export QT_QPA_PLATFORM=wayland
export QT_QPA_PLATFORMTHEME=KDE
export QT_WAYLAND_DISABLE_WINDOWDECORATION=1
export EGL_PLATFORM=wayland
export QT_QUICK_CONTROLS_STYLE=org.kde.breeze
export QT_ENABLE_GLYPH_CACHE_WORKAROUND=1
export QT_QUICK_CONTROLS_MOBILE=1
export KSCREEN_BACKEND=QScreen
export KDE_FULL_SESSION=1
export KDE_SESSION_VERSION=6
export XDG_MENU_PREFIX=plasma-
export PLASMA_INTEGRATION_USE_PORTAL=1
export PLASMA_PLATFORM=phone:handset
export PLASMA_DEFAULT_SHELL=org.kde.plasma.mobileshell
export XDG_CONFIG_DIRS="$HOME/.config/plasma-mobile:/etc/xdg:${XDG_CONFIG_DIRS:-}"
export GDK_BACKEND=wayland,x11
export SDL_VIDEODRIVER=wayland,x11

if [ -n "${BL_DEBUG_DIR:-}" ]; then
  mkdir -p "$BL_DEBUG_DIR" 2>/dev/null || true
  exec >>"$BL_DEBUG_DIR/desktop.log" 2>&1
  echo "== droiddeck-plasma-mobile $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${BL_WIDTH:-1280}x${BL_HEIGHT:-720}"
fi

if ! command -v plasmashell >/dev/null 2>&1 || ! command -v dbus-run-session >/dev/null 2>&1; then
  echo "== Plasma Mobile packages are missing; choose KDE Plasma Mobile in Desktop settings and start Desktop once"
  exit 66
fi

plasma_log="${BL_DEBUG_DIR:-/tmp}/plasma.log"
echo "== Plasma $(plasmashell --version 2>&1)"
echo "== Wayland display ${WAYLAND_DISPLAY:-wayland-0}; XDG runtime $XDG_RUNTIME_DIR"
mkdir -p /tmp || exit 73
chmod 1777 /tmp || echo "== could not set standard temporary-directory permissions"
export TMPDIR=/tmp
echo "== temporary directories: $(ls -ld /tmp /dev/shm 2>&1)"
echo "== preparing the KDE Plasma Mobile Wayland session"
: >"$plasma_log"

# Gamescope's Zink override is for game clients. KWin owns the Plasma Mobile session and presents
# one nested Wayland window through Bannerlator's host compositor.
export QT_QUICK_BACKEND=software
unset MESA_LOADER_DRIVER_OVERRIDE GALLIUM_DRIVER LIBGL_KOPPER_DRI2 ZINK_DESCRIPTORS mesa_glthread MESA_NO_ERROR

# The PRoot guest has no systemd user manager. Hide only its session-bus activation entry while
# KDE starts, and restore it on every exit.
systemd_dbus_service=/usr/share/dbus-1/services/org.freedesktop.systemd1.service
systemd_dbus_service_disabled="$systemd_dbus_service.droiddeck-disabled"
restore_systemd_dbus_service() {
  if [ -e "$systemd_dbus_service_disabled" ] && [ ! -e "$systemd_dbus_service" ]; then
    mv "$systemd_dbus_service_disabled" "$systemd_dbus_service" || echo "== could not restore systemd D-Bus service file"
  fi
}
restore_systemd_dbus_service
if [ -f "$systemd_dbus_service" ]; then
  mv "$systemd_dbus_service" "$systemd_dbus_service_disabled" || echo "== could not disable session-bus activation for systemd1"
fi
trap restore_systemd_dbus_service EXIT
dbus-run-session -- env XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" plasma_log="$plasma_log" sh -c '
    export WAYLAND_DISPLAY=wayland-0
    width=${BL_WIDTH:-1280}
    height=${BL_HEIGHT:-720}
    rm -f "$XDG_RUNTIME_DIR/wayland-1" "$XDG_RUNTIME_DIR/wayland-1.lock"
    # D-Bus activation inherited the outer compositor socket. KDE services activated later must
    # connect to the nested socket, while KWin itself continues to connect to the outer one.
    if command -v dbus-update-activation-environment >/dev/null 2>&1; then
      WAYLAND_DISPLAY=wayland-1 dbus-update-activation-environment WAYLAND_DISPLAY >>"$plasma_log" 2>&1
      echo "== D-Bus activation Wayland display update status $?"
    fi
    if command -v plasma-mobile-envmanager >/dev/null 2>&1; then
      echo "== applying Plasma Mobile device settings"
      QT_QPA_PLATFORM=offscreen plasma-mobile-envmanager --apply-settings >>"$plasma_log" 2>&1
      echo "== Plasma Mobile environment setup status $?"
    else
      echo "== plasma-mobile-envmanager is missing"
    fi
    # This guest has no interactive login from which the user can set a Linux password. The Plasma
    # Mobile PIN keypad authenticates that account password, so an idle/lock event can strand a
    # device user at a screen they cannot unlock. Keep session locking disabled for this embedded
    # desktop and let Android own the device lock instead.
    lock_config="${XDG_CONFIG_HOME:-$HOME/.config}/kscreenlockerrc"
    mkdir -p "$(dirname "$lock_config")"
    if command -v kwriteconfig6 >/dev/null 2>&1; then
      kwriteconfig6 --file "$lock_config" --group Daemon --key Autolock false
      kwriteconfig6 --file "$lock_config" --group Daemon --key LockOnResume false
      kwriteconfig6 --file "$lock_config" --group Daemon --key RequirePassword false
      kwriteconfig6 --file "$lock_config" --group Daemon --key Timeout 0
      echo "== disabled Plasma screen locking in $lock_config"
    else
      echo "== kwriteconfig6 is missing; could not disable Plasma screen locking"
    fi
    if command -v kbuildsycoca6 >/dev/null 2>&1; then
      echo "== building KDE service cache"
      QT_QPA_PLATFORM=offscreen kbuildsycoca6 --noincremental >>"$plasma_log" 2>&1
      cache_status=$?
      echo "== KDE service cache status $cache_status"
      cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}
      for cache_file in "$cache_dir"/ksycoca6_*; do
        [ -f "$cache_file" ] || continue
        # KDE cache files land write-only under this PRoot user and cannot be reopened by service lookups.
        chmod u+rw "$cache_file" || echo "== could not make KDE cache readable: $cache_file"
      done
    else
      echo "== kbuildsycoca6 is missing"
    fi
    effect_config="${XDG_CONFIG_HOME:-$HOME/.config}/kwinrc"
    if command -v kwriteconfig6 >/dev/null 2>&1; then
      # The overview control in Plasma Mobile invokes this KWin effect. Keep it explicitly enabled
      # so the patched state/gesture initialization is active in the embedded session.
      kwriteconfig6 --file "$effect_config" --group Plugins --key mobiletaskswitcherEnabled true
    fi
    if command -v kreadconfig6 >/dev/null 2>&1; then
      effect_setting=$(kreadconfig6 --file "$effect_config" \
        --group Plugins --key mobiletaskswitcherEnabled 2>&1 || true)
      echo "== mobile task-switcher setting in $effect_config: ${effect_setting:-unset}"
    else
      echo "== kreadconfig6 is missing; cannot inspect the mobile task-switcher setting"
    fi
    echo "== starting nested KWin and Plasma Mobile on wayland-0 (${width}x${height}), socket wayland-1"
    # The mobile task switcher queries Workspace::activities() while filtering tasks.
    # Keep KActivities initialized; --no-kactivities makes the overview crash on activation.
    KWIN_WAYLAND_NO_PERMISSION_CHECKS=1 kwin_wayland \
      --xwayland \
      --wayland-display=wayland-0 \
      --socket=wayland-1 \
      --width="$width" --height="$height" --fullscreen \
      --no-lockscreen \
      --exit-with-session "plasmashell -p org.kde.plasma.mobileshell --replace" \
      >>"$plasma_log" 2>&1 &
    kwin_pid=$!
    cleanup() {
      if [ -n "$kwin_pid" ]; then kill "$kwin_pid" 2>/dev/null || true; wait "$kwin_pid" 2>/dev/null || true; fi
    }
    trap cleanup EXIT INT TERM
    wait "$kwin_pid"
  ' >>"$plasma_log" 2>&1
result=$?
restore_systemd_dbus_service
trap - EXIT
echo "== Plasma Mobile session exited (status $result)"
exit "$result"
