#!/bin/sh
# Launcher for the WASEL desktop app on Linux: installed as /usr/bin/wasel by the .deb, used by the AppImage's AppRun.
# It picks the rendering path before the app starts:
#
#   - Inside a virtual machine (VMware, VirtualBox, QEMU/KVM, Hyper-V, Parallels) the virtual graphics card's OpenGL
#     is a known way to get the window drawn upside down and, under GNOME on Wayland, to take the desktop down with
#     it. There the app draws without the graphics card (Mesa's software renderer) and on X11 (Xwayland).
#   - WASEL_GL=native keeps the graphics card anywhere; WASEL_GL=software forces the safe path anywhere.
#
# Everything else is passed through (a wasel:// link from the URL handler).
app="${WASEL_APP:-/opt/wasel/wasel}"
mode="${WASEL_GL:-auto}"
if [ "$mode" = auto ]; then
  virt="$(systemd-detect-virt --vm 2>/dev/null || true)"
  case "$virt" in
    none|"") mode=native ;;
    *) mode=software ;;
  esac
fi
if [ "$mode" = software ]; then
  export LIBGL_ALWAYS_SOFTWARE=1
  export GALLIUM_DRIVER="${GALLIUM_DRIVER:-llvmpipe}"
  # the software renderer starts one thread per CPU and glibc one memory arena per thread: on a machine with many
  # cores that costs about 1 GB. Two threads draw this window fine; the arenas are capped the same way.
  export LP_NUM_THREADS="${LP_NUM_THREADS:-2}"
  export MALLOC_ARENA_MAX="${MALLOC_ARENA_MAX:-2}"
  # X11 when a display is there (Xwayland under GNOME); Wayland-only sessions keep their backend
  if [ -n "$DISPLAY" ]; then export GDK_BACKEND=x11; fi
fi
exec "$app" "$@"
