#!/bin/bash
# dde-desktop-session - canonical launcher for the Deepin Desktop Environment
# (treeland Wayland compositor + dde-shell) on Amazon Linux 2023.
#
# Works both on a normal seat (treeland on the DRM/auto backend) and headless
# (treeland nested in an existing X server via the wlroots X11 backend with the
# software renderer). Set DDE_HEADLESS=1 to force the headless/software path,
# which is the default when DISPLAY is set but no DRM device is usable.
set -e

log() { echo "[dde-desktop-session] $*"; }

export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
mkdir -p "$XDG_RUNTIME_DIR"; chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null || true
export XDG_CURRENT_DESKTOP=DDE
export XDG_SESSION_DESKTOP=deepin

# The desktop organizer expects ~/Desktop to exist.
mkdir -p "$HOME/Desktop" 2>/dev/null || true

# --- session D-Bus ---
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
    eval "$(dbus-launch --sh-syntax)"
    export DBUS_SESSION_BUS_ADDRESS
fi
dbus-update-activation-environment --all 2>/dev/null || true

# --- headless / software-rendering detection (no GPU, e.g. EC2) ---
if [ "${DDE_HEADLESS:-}" = "1" ] || { [ -n "$DISPLAY" ] && [ ! -e /dev/dri/card0 ]; }; then
    log "headless mode: treeland nested in X ($DISPLAY) with software renderer"
    export WLR_BACKENDS=x11
    export WLR_RENDERER=pixman
    export WLR_X11_OUTPUTS="${WLR_X11_OUTPUTS:-1}"
    export LIBGL_ALWAYS_SOFTWARE=1
    export GALLIUM_DRIVER=llvmpipe
fi

# --- start the treeland Wayland compositor ---
log "starting treeland"
treeland &
TREELAND_PID=$!

# wait for the Wayland socket
for i in $(seq 1 40); do
    [ -S "$XDG_RUNTIME_DIR/wayland-0" ] && break
    kill -0 "$TREELAND_PID" 2>/dev/null || { log "treeland exited early"; exit 1; }
    sleep 0.5
done
export WAYLAND_DISPLAY=wayland-0
log "compositor up: WAYLAND_DISPLAY=$WAYLAND_DISPLAY"

# --- DDE clients connect to treeland as Wayland clients ---
export QT_QPA_PLATFORM=wayland
# NOTE: do NOT set QT_WAYLAND_SHELL_INTEGRATION=layer-shell — it crashes Qt
# wayland clients; dde-shell uses its own layer-shell client implementation.
unset QT_WAYLAND_SHELL_INTEGRATION

# appearance / theme / wallpaper service host
deepin-service-manager &
# application lifecycle manager
dde-application-manager &
sleep 1
# backend daemon
dde-daemon 2>/dev/null &

sleep 1
# the shell: dock + panels (desktop plugin runs as its own process)
dde-shell -C DDE -d org.deepin.ds.desktop &
sleep 1
# the desktop: icons/canvas (wallpaper is drawn by treeland itself)
dde-shell -p org.deepin.ds.desktop &
# polkit agent
[ -x /usr/lib/polkit-1-dde/dde-polkit-agent ] && /usr/lib/polkit-1-dde/dde-polkit-agent &

log "DDE session started"
# keep the session alive as long as the compositor runs
wait "$TREELAND_PID"
