#!/bin/sh
# mjdev desktop wayland session
# started by the display manager via /usr/share/wayland-sessions/mjdev.desktop

export XDG_CURRENT_DESKTOP=mjdev
export XDG_SESSION_TYPE=wayland
export MOZ_ENABLE_WAYLAND=1
export QT_QPA_PLATFORM="wayland;xcb"
export _JAVA_AWT_WM_NONREPARENTING=1
# allow wlroots to start on llvmpipe (software GL). On real hardware mesa uses the
# GPU and this is ignored; in a VM / headless box without GPU passthrough mesa falls
# back to llvmpipe and wlroots otherwise refuses to create a renderer ("Software
# rendering detected, please use WLR_RENDERER_ALLOW_SOFTWARE") and the compositor
# exits immediately -> black screen + tty1 autologin crash-loop.
export WLR_RENDERER_ALLOW_SOFTWARE=1
# NOTE: SKIKO_RENDER_API is intentionally NOT set here. The compositor (mjdevc) detects at runtime
# whether it got a hardware or software GL renderer and exports SKIKO_RENDER_API=SOFTWARE for the
# shell only when GL is software (VM / no GPU) — so real GPUs use hardware GL automatically.

# desktop shell binary - deb/appimage install location, gradle dev fallback
SHELL_CMD="/opt/mjdev-desktop/bin/mjdev-desktop"
if [ ! -x "$SHELL_CMD" ]; then
    SHELL_CMD="$HOME/.local/bin/mjdev-desktop"
fi

# compositor binary - /usr/bin (deb) or /usr/local/bin (manual install)
MJDEVC="$(command -v mjdevc 2>/dev/null)"
if [ -z "$MJDEVC" ]; then
    MJDEVC="/usr/bin/mjdevc"
fi

# clean up the activation environment the compositor exported into the
# persistent systemd --user manager. with KillUserProcesses=no (the distro
# default) that manager survives logout, so leaving a stale WAYLAND_DISPLAY /
# DISPLAY behind poisons the next login - of any session, not just ours.
# run on every exit path (normal exit, crash, signal) - no exec, so we get here.
cleanup() {
    systemctl --user unset-environment \
        WAYLAND_DISPLAY DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE \
        2>/dev/null || true
}
trap cleanup EXIT HUP INT TERM

# log the compositor + shell output so a failed start is diagnosable (otherwise the
# tty1 session just dies to a black screen with no trace). keep the previous run.
LOG_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/mjdev-desktop"
mkdir -p "$LOG_DIR"
[ -f "$LOG_DIR/session.log" ] && mv -f "$LOG_DIR/session.log" "$LOG_DIR/session.log.1"
"$MJDEVC" --session --shell-cmd "$SHELL_CMD" >"$LOG_DIR/session.log" 2>&1
