#!/usr/bin/env bash
set -euo pipefail

bin="${ENIGMA_BIN:-$HOME/.local/lib/enigma/enigma}"
if [[ ! -x "$bin" ]]; then
    echo "enigma: installed binary not found at $bin" >&2
    exit 127
fi

foreground="${ENIGMA_FOREGROUND:-}"
if [[ "${1:-}" == "--foreground" ]]; then
    foreground=1
    shift
fi

# Prefer Vulkan for installed Linux launches. On some Mesa setups wgpu
# auto-selects the GL/EGL path, which can hang during surface creation before
# the window becomes visible. Users can still override explicitly:
#   WGPU_BACKEND=gl enigma
: "${WGPU_BACKEND:=vulkan}"
export WGPU_BACKEND

# WSL2 uses Mesa's dzn (D3D12→Vulkan) as the Vulkan ICD for the real GPU.
# wgpu 29 hides non-conformant adapters by default (dzn has
# conformance_version.major == 0). Tell wgpu to keep it — dzn works fine
# for rendering even though it hasn't passed Khronos conformance.
if [[ -n "${WSL_DISTRO_NAME:-}" ]]; then
    : "${WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER:=1}"
    export WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER
fi

# WSLg uses Wayland natively. With the Vulkan-only backend (dzn driver),
# Wayland presentation works correctly. Pin DPI/cursor scale so the
# pointer is not oversized. Users can force X11 with ENIGMA_WSL_X11=1.
if [[ -n "${WSL_DISTRO_NAME:-}" ]]; then
    if [[ -n "${ENIGMA_WSL_X11:-}" ]]; then
        unset WAYLAND_DISPLAY
        unset WAYLAND_SOCKET
        : "${WINIT_X11_SCALE_FACTOR:=1}"
        : "${XCURSOR_SIZE:=24}"
        export WINIT_X11_SCALE_FACTOR XCURSOR_SIZE
    else
        : "${WINIT_WAYLAND_SCALE_FACTOR:=1}"
        export WINIT_WAYLAND_SCALE_FACTOR
    fi
fi

# Shell profiles sometimes force Mesa's Zink OpenGL driver globally. That is
# useful for some apps but breaks Enigma on machines where EGL/Zink cannot pick
# a physical device. Preserve non-zink values and allow opting out with:
#   ENIGMA_KEEP_MESA_OVERRIDES=1 enigma
if [[ -z "${ENIGMA_KEEP_MESA_OVERRIDES:-}" ]]; then
    if [[ "${MESA_LOADER_DRIVER_OVERRIDE:-}" == "zink" ]]; then
        unset MESA_LOADER_DRIVER_OVERRIDE
    fi
    if [[ "${GALLIUM_DRIVER:-}" == "zink" || "${GALLIUM_DRIVER:-}" == "d3d12" ]]; then
        unset GALLIUM_DRIVER
    fi
fi

if [[ -n "$foreground" ]]; then
    exec "$bin" "$@"
fi

state_home="${XDG_STATE_HOME:-$HOME/.local/state}"
log_dir="$state_home/enigma"
mkdir -p "$log_dir"
log_file="$log_dir/enigma.log"

if command -v setsid >/dev/null 2>&1; then
    setsid -f "$bin" "$@" >>"$log_file" 2>&1 < /dev/null
else
    nohup "$bin" "$@" >>"$log_file" 2>&1 < /dev/null &
fi
