#!/bin/sh
# Aqueous init wrapper.
#
# Installed as /usr/bin/aqueous-init and run by Aqueous as its `-c` child:
#
#     exec aqueous -c '/usr/bin/aqueous-init'
#
# Aqueous now applies display configuration directly through wlroots before
# this child is launched and owns the outputd-compatible Unix socket itself.
# This wrapper seeds shell configuration, exports the live session environment,
# starts the graphical-session targets, then exits. Window-management policy
# runs inside the compositor.
set -u

# Seed the Noctalia (v5) default config on first launch. Idempotent and
# non-destructive: only runs when the user has no config.toml yet. Noctalia v5
# reads every *.toml in ~/.config/noctalia/ and merges them; we seed the
# hand-written base layer (config.toml) with Aqueous defaults (idle/lock
# timeouts, blurred lock screen, default wallpapers pointing at
# /usr/share/aqueous/wallpapers). GUI changes land in
# ~/.local/state/noctalia/settings.toml and are never touched here.
NOCTALIA_USER_CFG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/noctalia"
NOCTALIA_DEFAULTS="/usr/share/aqueous/noctalia/config.toml"
if [ ! -e "$NOCTALIA_USER_CFG_DIR/config.toml" ] && [ -r "$NOCTALIA_DEFAULTS" ]; then
    mkdir -p "$NOCTALIA_USER_CFG_DIR"
    cp "$NOCTALIA_DEFAULTS" "$NOCTALIA_USER_CFG_DIR/config.toml"
    chmod 600 "$NOCTALIA_USER_CFG_DIR/config.toml"
fi

# Push the live Wayland and native XWayland environment into systemd --user
# and D-Bus so services and desktop-launched applications connect to this
# compositor. This must run here, not in aqueous-wm.sh, because
# WAYLAND_DISPLAY and DISPLAY are allocated only after Aqueous starts.
# The GPU-pin vars (MESA_VK_DEVICE_SELECT/__GLX_VENDOR_LIBRARY_NAME/DRI_PRIME/
# __NV_PRIME_RENDER_OFFLOAD) are set by Aqueous on this process's environment
# only on multi-GPU systems (empty on single-GPU). Forwarding them in the bare
# KEY form means the tools silently skip any that are unset, so this is inert on
# single-GPU machines and pins .desktop/systemd-launched apps to the same GPU
# the compositor renders on, closing the last launch path that could straddle
# two GPU stacks (the dual-GPU GObject toggle-ref crash).
display_var=""
[ -n "${DISPLAY:-}" ] && display_var="DISPLAY"

if command -v uwsm >/dev/null 2>&1 && [ -n "${UWSM_FINALIZE_SOCK:-}${WAYLAND_DISPLAY:-}" ]; then
    # uwsm owns the session lifecycle: `uwsm finalize` exports the (now-live)
    # Wayland env into the systemd --user + D-Bus activation environments AND
    # signals uwsm that the compositor is up, so it activates the real
    # graphical-session.target itself (satisfying xdg-desktop-portal's
    # Requisite=graphical-session.target) and pulls in xdg-desktop-autostart.target.
    # Crucially it re-exports the current WAYLAND_DISPLAY and native XWayland
    # DISPLAY on every start, so a compositor restart leaves no stale endpoint
    # pinned in the user manager.
    # The GPU-pin vars (set by Aqueous only on multi-GPU systems) are forwarded
    # in bare KEY form so uwsm silently skips any that are unset on single-GPU.
    # shellcheck disable=SC2086
    uwsm finalize \
        WAYLAND_DISPLAY \
        $display_var \
        XDG_CURRENT_DESKTOP \
        XDG_SESSION_TYPE \
        XDG_RUNTIME_DIR \
        XCURSOR_THEME \
        XCURSOR_SIZE \
        MESA_VK_DEVICE_SELECT \
        __GLX_VENDOR_LIBRARY_NAME \
        DRI_PRIME \
        __NV_PRIME_RENDER_OFFLOAD 2>/dev/null || true
else
    # Fallback for sessions launched WITHOUT uwsm (e.g. a display manager that
    # execs aqueous-wm directly). Push the live session display environment
    # into systemd --user and D-Bus, then bring the graphical session up via
    # the aqueous-session.target wrapper (static
    # graphical-session.target has RefuseManualStart).
    if command -v dbus-update-activation-environment >/dev/null 2>&1; then
        # shellcheck disable=SC2086
        dbus-update-activation-environment --systemd \
            WAYLAND_DISPLAY \
            $display_var \
            XDG_CURRENT_DESKTOP=Aqueous \
            XDG_SESSION_TYPE=wayland \
            XDG_RUNTIME_DIR \
            MESA_VK_DEVICE_SELECT \
            __GLX_VENDOR_LIBRARY_NAME \
            DRI_PRIME \
            __NV_PRIME_RENDER_OFFLOAD 2>/dev/null || true
    elif command -v systemctl >/dev/null 2>&1; then
        # Only import vars that are actually set, so older systemd versions never
        # warn on unset names (keeps the single-GPU case clean).
        gpu_vars=""
        for v in MESA_VK_DEVICE_SELECT __GLX_VENDOR_LIBRARY_NAME DRI_PRIME __NV_PRIME_RENDER_OFFLOAD; do
            eval "val=\${$v:-}"
            [ -n "$val" ] && gpu_vars="$gpu_vars $v"
        done
        # shellcheck disable=SC2086
        systemctl --user import-environment \
            WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_TYPE XDG_RUNTIME_DIR \
            $display_var $gpu_vars \
            2>/dev/null || true
    fi

    systemctl --user start aqueous-session.target 2>/dev/null || true
    systemctl --user start xdg-desktop-autostart.target 2>/dev/null || true
fi

# Kick the portal in case it already failed earlier in the boot.
# reset-failed clears the start-limit so the restart actually runs.
systemctl --user reset-failed xdg-desktop-portal-gtk.service 2>/dev/null || true
systemctl --user restart xdg-desktop-portal.service xdg-desktop-portal-gtk.service xdg-desktop-portal-wlr.service 2>/dev/null || true

exit 0
