#!/usr/bin/env bash
# Lumen launcher wrapper.
#
# It execs a private copy of the Python interpreter named "lumen" when one is
# installed: KWin derives the resource class of layer-shell windows from the
# client executable's file name, so this is what makes the launcher appear as
# "lumen" (instead of "python") in KWin's window detection and rules.

set -u

# Fast path: if the resident Lumen daemon is already on D-Bus and no arguments
# (or "toggle") were passed, activate it directly via gdbus (~3 ms) instead of
# cold-starting a second Python + GTK4 interpreter (~200 ms).
if [[ $# -eq 0 || ( $# -eq 1 && "$1" == "toggle" ) ]]; then
    if command -v gdbus >/dev/null 2>&1; then
        if gdbus call --session --dest eu.ncsk.Lumen --object-path /eu/ncsk/Lumen --method org.gtk.Application.Activate "{}" >/dev/null 2>&1; then
            exit 0
        fi
    fi
fi

# Clipboard history opens through a GAction so the hotkey does not cold-start
# a second Python/GTK process while the resident daemon is alive.
if [[ $# -eq 1 && "$1" == "clip" ]]; then
    if command -v gdbus >/dev/null 2>&1; then
        if gdbus call --session --dest eu.ncsk.Lumen --object-path /eu/ncsk/Lumen --method org.gtk.Actions.Activate "clipboard-history" "[]" "{}" >/dev/null 2>&1; then
            exit 0
        fi
    fi
fi

ROOT="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)"

# Prefer an interpreter named "lumen" so KWin/Wayland assigns the resource
# class as "lumen" instead of generic "python".
INTERP=""
if [[ -n "${LUMEN_INTERP:-}" && -f "$LUMEN_INTERP" && -x "$LUMEN_INTERP" ]]; then
    INTERP="$LUMEN_INTERP"
elif [[ -f "$ROOT/lumen-bin" && -x "$ROOT/lumen-bin" ]]; then
    INTERP="$ROOT/lumen-bin"
elif [[ -f "$ROOT/lumen" && -x "$ROOT/lumen" ]]; then
    INTERP="$ROOT/lumen"
elif [[ -f "$HOME/.local/share/lumen/lumen" && -x "$HOME/.local/share/lumen/lumen" ]]; then
    INTERP="$HOME/.local/share/lumen/lumen"
fi

# Preload libgtk4-layer-shell.so before libgtk-4.so so GTK4 hooks wl_surface
# creation for zwlr_layer_shell_v1 on Niri/Wayland.
export LD_PRELOAD="libgtk4-layer-shell.so${LD_PRELOAD:+:$LD_PRELOAD}"

if [[ -n "$INTERP" ]]; then
    if "$INTERP" -c "import gi" >/dev/null 2>&1; then
        exec "$INTERP" "$ROOT/bin/lumen.py" "$@"
    fi
fi

exec python3 "$ROOT/bin/lumen.py" "$@"
