#!/bin/sh
# Aqueous-Git session launcher.
export AQUEOUS_SHARE_DIR="/usr/share/aqueous-git"
export AQUEOUS_SESSION_RUNTIME="/usr/lib/aqueous-git/session-runtime.sh"
export AQUEOUS_SYSCONFDIR="/etc"
export AQUEOUS_UNIT_DIR="/usr/lib/systemd/user"
# Installed as /usr/bin/aqueous-wm-git and referenced by the Wayland
# session entry at /usr/share/wayland-sessions/aqueous-git.desktop.
#
# NOTE: deliberately *not* using `set -e` — a single non-fatal failure
# (e.g. mkdir on an already-correct XDG_RUNTIME_DIR under SDDM) must not
# abort the whole session.

export XDG_CURRENT_DESKTOP=Aqueous-Git
session_runtime=${AQUEOUS_SESSION_RUNTIME:-/usr/lib/aqueous-git/session-runtime.sh}
if [ -x "$session_runtime" ]; then
    selected_desktop=$("$session_runtime" portal-identity selection) && export XDG_CURRENT_DESKTOP="$selected_desktop"
fi
export XDG_SESSION_TYPE=wayland
export XDG_SESSION_DESKTOP=Aqueous-Git

# Toolkit backend hints. Apps prefer Wayland and fall back to the XWayland
# server managed directly by Aqueous-Git when the native Wayland path is unavailable.
export QT_QPA_PLATFORM="wayland;xcb"
export GDK_BACKEND="wayland,x11"
export SDL_VIDEODRIVER="wayland,x11"
export CLUTTER_BACKEND=wayland
export MOZ_ENABLE_WAYLAND=1
# Fixes the grey-blob / non-reparenting Java/Swing/JetBrains bug under any
# non-reparenting WM, including Aqueous-Git's native XWayland integration.
export _JAVA_AWT_WM_NONREPARENTING=1

# Do not inherit the display manager's X server. Aqueous-Git creates XWayland and
# exports the correct DISPLAY to its session init command after startup.
unset DISPLAY

# Do not manufacture XCURSOR_THEME/XCURSOR_SIZE here. The compositor and
# XWayland inherit user-provided values, while leaving them unset lets
# libXcursor follow the user's normal default-theme lookup instead of pinning
# every new session to an Aqueous-Git-owned Adwaita default.

export AQUEOUS_MOD="${AQUEOUS_MOD:-Super}"

export AQUEOUS_NESTED=0

# Ensure XDG_RUNTIME_DIR exists (greetd/sddm normally provide this via
# pam_systemd). Tolerate failures: under SDDM the directory may already
# exist with strict ownership we cannot chmod.
if [ -z "${XDG_RUNTIME_DIR:-}" ]; then
    export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
[ -d "$XDG_RUNTIME_DIR" ] || mkdir -p "$XDG_RUNTIME_DIR" 2>/dev/null || true
chmod 0700 "$XDG_RUNTIME_DIR" 2>/dev/null || true

# Redirect stdout/stderr to a per-user log so failures launching from
# sddm/greetd (where there is no attached terminal) are diagnosable.
# Truncate (not append) — XDG_RUNTIME_DIR is tmpfs but auto-login +
# systemd lingering can otherwise grow this without bound.
LOG="$XDG_RUNTIME_DIR/aqueous-wm-git.log"
exec >"$LOG" 2>&1
echo "[aqueous-wm-git] $(date -Is) starting uid=$(id -u) greeter=${XDG_GREETER_DATA_DIR:-unknown}"

# NOTE: the Wayland environment (WAYLAND_DISPLAY etc.) is NOT exported into
# systemd --user / D-Bus here — at this point Aqueous-Git has not started yet,
# so WAYLAND_DISPLAY is not valid. That export now happens from
# /usr/bin/aqueous-init-git once the compositor is up, via `uwsm finalize` (when
# launched under uwsm) or a dbus/systemctl fallback otherwise. This avoids
# pinning a stale/empty WAYLAND_DISPLAY into the user manager.

# Seed user config from the system default if missing. Never overwrite.
cfg="${XDG_CONFIG_HOME:-$HOME/.config}/aqueous-git/wm.toml"
if [ ! -f "$cfg" ] && [ -f /etc/xdg/aqueous-git/wm.toml ]; then
    # Non-fatal: a quirky $HOME/.config (e.g. odd ownership during a
    # greetd autologin handoff) must not abort the whole session. Aqueous-Git
    # will fall back to /etc/xdg/aqueous-git/wm.toml at runtime.
    install -Dm644 /etc/xdg/aqueous-git/wm.toml "$cfg" 2>/dev/null || true
fi

# Seed the inert output template separately. All declarations are commented,
# so existing wm.toml display policy remains unchanged until the user opts in.
outputs_cfg="${XDG_CONFIG_HOME:-$HOME/.config}/aqueous-git/outputs.toml"
if [ ! -f "$outputs_cfg" ] && [ -f /etc/xdg/aqueous-git/outputs.toml ]; then
    install -Dm644 /etc/xdg/aqueous-git/outputs.toml "$outputs_cfg" 2>/dev/null || true
fi

# Seed the inert input template too. Without a user-owned input.toml, input
# settings (pointer acceleration, tap-to-click, natural scroll, and XKB
# policy) resolve to the read-only packaged default under /etc/xdg, where the
# configuration helper must refuse to write them. The seeded file is fully
# commented, so behavior is unchanged until a key is uncommented or a desktop
# settings tool writes it.
input_cfg="${XDG_CONFIG_HOME:-$HOME/.config}/aqueous-git/input.toml"
if [ ! -f "$input_cfg" ] && [ -f /etc/xdg/aqueous-git/input.toml ]; then
    install -Dm644 /etc/xdg/aqueous-git/input.toml "$input_cfg" 2>/dev/null || true
fi

# Seed the inert layout template as well. A root-owned system layout.toml is
# still common on managed and upgraded systems, and the layout sidecar is
# discovered ahead of $AQUEOUS_LAYOUT and [layout].path, so layout edits
# (gaps, borders, slots, stacking and snap zones) would otherwise persist
# through a file the configuration helper must refuse to write. Skip the seed
# when an explicit sidecar is configured, because the user file would shadow
# it; an active path assignment is one whose line is not commented out.
layout_seed=true
if [ -n "${AQUEOUS_LAYOUT:-}" ]; then
    layout_seed=false
elif [ -f "$cfg" ] && awk '
    /^[[:space:]]*\[/ { in_layout = ($0 ~ /^[[:space:]]*\[layout\][[:space:]]*$/) }
    in_layout && /^[[:space:]]*path[[:space:]]*=/ { found = 1; exit }
    END { exit !found }
' "$cfg"; then
    layout_seed=false
fi
layout_cfg="${XDG_CONFIG_HOME:-$HOME/.config}/aqueous-git/layout.toml"
if $layout_seed && [ ! -f "$layout_cfg" ] && [ -f /etc/xdg/aqueous-git/layout.toml ]; then
    install -Dm644 /etc/xdg/aqueous-git/layout.toml "$layout_cfg" 2>/dev/null || true
fi

# Aqueous-Git runs the compositor, window-management policy, input, and output
# configuration in one process. aqueous-init-git is its short-lived `-c` child and
# exports the live session environment.
# Run (not exec) so the wrapper can tear down the graphical session target
# after the compositor exits. Use an absolute path because display-manager
# session PATH values are often minimal.
# Stop a daemon left running across an upgrade from a pre-cutover package so it
# cannot retain the output socket. Current packages do not ship or start it.
/usr/bin/aqueous-git -c /usr/bin/aqueous-init-git
status=$?
echo "[aqueous-wm-git] $(date -Is) aqueous-git exited status=$status"

# Tear down the graphical session wrapper so everything PartOf/BindsTo
# graphical-session.target (including the portals) stops cleanly.
# BindsTo should already do this, but stop it explicitly for robustness.
if command -v systemctl >/dev/null 2>&1; then
    systemctl --user stop aqueous-git-session.target 2>/dev/null || true
fi

exit $status
