#!/bin/sh
# Rendered from launcher.sh.in by Expand-LinuxPackagingTemplates. /usr/share/mindmap_chat is the
# directory the app bundle is installed into, and it differs by package format:
#   .deb / .rpm  -> /usr/share/mindmap_chat
#   Flatpak      -> /app/share/mindmap_chat   (there is no /usr to write to)
#
# The Flathub .deb is baked with /usr/share/mindmap_chat=/app/share/mindmap_chat because the
# Flatpak manifest relocates the payload there. That same .deb is also installable
# directly (the payload physically ships under /usr/share), so we resolve APP_ROOT
# at runtime: use the baked path when the binary is actually there (the sandbox),
# otherwise fall back to /usr/share. Without this, a directly-installed Flathub
# .deb execs /app/share/... and dies with "not found".
_BAKED_ROOT='/usr/share/mindmap_chat'
if [ -x "$_BAKED_ROOT/mindmap_chat" ]; then
  APP_ROOT="$_BAKED_ROOT"
else
  APP_ROOT='/usr/share/mindmap_chat'
fi
#
# The LD_LIBRARY_PATH export below is what makes libonnxruntime.so resolve inside a
# Flatpak: the .deb/.rpm ALSO register the lib dir via /etc/ld.so.conf.d + ldconfig,
# but neither exists in a sandbox, so this export is the sandbox's only mechanism.
# Do not remove it as "redundant" — it is redundant only on deb/rpm.
# ── Startup log ───────────────────────────────────────────────────────────────
_LOG_DIR="$HOME/.local/share/mindmap_chat/logs"
mkdir -p "$_LOG_DIR"
_LOG_FILE="$_LOG_DIR/startup-$(date '+%Y%m%d-%H%M%S').log"
# Keep last 20 startup log files
ls -1t "$_LOG_DIR"/startup-*.log 2>/dev/null | tail -n +21 | xargs rm -f 2>/dev/null
{
  printf '=== MindMap Chat %s ===\n' "$(date '+%Y-%m-%dT%H:%M:%S')"
  printf 'display  : DISPLAY=%s  WAYLAND_DISPLAY=%s\n' "'$DISPLAY'" "'$WAYLAND_DISPLAY'"
  printf 'session  : XDG_SESSION_TYPE=%s  XDG_CURRENT_DESKTOP=%s\n' "'$XDG_SESSION_TYPE'" "'$XDG_CURRENT_DESKTOP'"
  printf 'gl-env   : GDK_BACKEND=%s  GDK_DEBUG=%s  LIBGL_ALWAYS_SOFTWARE=%s\n' "'$GDK_BACKEND'" "'$GDK_DEBUG'" "'$LIBGL_ALWAYS_SOFTWARE'"
  printf 'glvnd    : __GLX_VENDOR_LIBRARY_NAME=%s\n' "'$__GLX_VENDOR_LIBRARY_NAME'"
  printf 'nvidia   : %s\n' "$(cat /proc/driver/nvidia/version 2>/dev/null | head -1 || printf 'not present')"
  printf 'gtk      : %s\n' "$(pkg-config --modversion gtk+-3.0 2>/dev/null || printf 'pkg-config unavailable')"
  printf '%s\n' '--- applying env fixes ---'
} >> "$_LOG_FILE"
# Clear stale GTK GL visual cache that can cause a GLX pixel-format failure when
# the cached X11 visual IDs (GDK_VISUALS root property) no longer match the
# GLX FBConfig list — seen on NVIDIA and after driver updates.
if [ -n "$DISPLAY" ]; then
  command -v xprop >/dev/null 2>&1 && xprop -root -remove GDK_VISUALS 2>/dev/null
fi
# Prefer the Wayland backend. On KDE + NVIDIA + X11, Flutter's GTK3 embedder
# renders a blank canvas (the X11/GLX path served by NVIDIA's GLVND vendor fails
# to present), and forcing software/Mesa GLX does not help. The native
# Wayland/EGL path renders correctly on the same hardware. Fall back to X11 only
# when no Wayland session is available. (XWayland sets DISPLAY too, so check
# WAYLAND_DISPLAY first.)
if [ -n "$WAYLAND_DISPLAY" ] && [ -z "$GDK_BACKEND" ]; then
  export GDK_BACKEND=wayland
elif [ -n "$DISPLAY" ] && [ -z "$GDK_BACKEND" ]; then
  export GDK_BACKEND=x11
fi
# Inside a Flatpak sandbox, force GTK's file choosers through the XDG Desktop
# Portal. file_selector uses GtkFileChooserNative, which is *supposed* to detect
# the sandbox and use the portal on its own, but that autodetection is unreliable
# across GTK builds — when it misfires the dialog falls back to an in-process
# chooser that, with no --filesystem permission, shows the user's home as empty.
# The portal is guaranteed to exist on every Flatpak host, so forcing it is safe
# and generic. Gate on /.flatpak-info so the .deb/.rpm builds are unaffected
# (GTK_USE_PORTAL on a bare desktop would needlessly reroute every dialog).
if [ -f /.flatpak-info ]; then
  export GTK_USE_PORTAL=1
fi
# Compatibility GSettings schema (bundled at /usr/share/mindmap_chat/schemas).
# On Wayland there is no XSETTINGS manager, so GDK 3.24 reads font settings from
# org.gnome.settings-daemon.plugins.xsettings via GSettings and asks for the
# 'antialiasing' key. gnome-settings-daemon 46 moved that key into the
# .deprecated sub-schema, so the read aborts and the app crashes before drawing.
# Prepending our schema dir makes GDK find a version that still defines the key.
export GSETTINGS_SCHEMA_DIR="$APP_ROOT/schemas${GSETTINGS_SCHEMA_DIR:+:$GSETTINGS_SCHEMA_DIR}"
{
  printf '%s\n' '--- env after fixes ---'
  printf 'GDK_BACKEND=%s  GDK_DEBUG=%s  GSETTINGS_SCHEMA_DIR=%s\n' "'$GDK_BACKEND'" "'$GDK_DEBUG'" "'$GSETTINGS_SCHEMA_DIR'"
  printf 'sandbox  : flatpak-info=%s  GTK_USE_PORTAL=%s\n' "$([ -f /.flatpak-info ] && printf yes || printf no)" "'$GTK_USE_PORTAL'"
} >> "$_LOG_FILE"
if [ -n "$LD_LIBRARY_PATH" ]; then
  export LD_LIBRARY_PATH=$APP_ROOT/lib:$LD_LIBRARY_PATH
else
  export LD_LIBRARY_PATH=$APP_ROOT/lib
fi
printf 'exec : %s/mindmap_chat\n' "$APP_ROOT" >> "$_LOG_FILE"
# G_MESSAGES_DEBUG=GDK captures GDK OpenGL context selection details.
# Binary stderr (GDK/GTK/GL messages) is appended to the startup log.
export G_MESSAGES_DEBUG="${G_MESSAGES_DEBUG:-GDK}"
exec "$APP_ROOT/mindmap_chat" "$@" 2>>"$_LOG_FILE"
