#!/bin/bash

# has_option is missing in lightdm-session
# https://bugs.launchpad.net/ubuntu/+source/xorg/+bug/1922414
# Define it here if missing. It's needed by some of the Xsession.d scripts
if ! has_option 2>/dev/null; then
    OPTIONS="$(
      if [ -r "$OPTIONFILE" ]; then
        cat "$OPTIONFILE"
      fi
      if [ -d /etc/X11/Xsession.options.d ]; then
        run-parts --list --regex '\.conf$' /etc/X11/Xsession.options.d | xargs -d '\n' cat
      fi
    )"
    has_option() {
      # Ensure that a later no-foo overrides an earlier foo
      if [ "$(echo "$OPTIONS" | grep -Eo "^(no-)?$1\>" | tail -n 1)" = "$1" ]; then
        return 0
      else
        return 1
      fi
    }
fi

# Use GCR as SSH agent if available
if [ -x /usr/libexec/gcr-ssh-agent ]; then
    export SSH_AUTH_SOCK="/run/user/$(id -u)/gcr/ssh"
fi

# Without 3D acceleration, force GTK4 to use OpenGL.
# Otherwise it picks vulkan/lavapipe and we get random crashes with GTK4 apps
if [ -z "$GSK_RENDERER" ] && command -v eglinfo >/dev/null 2>&1; then
    renderer=$(timeout 5 eglinfo -B -p surfaceless 2>/dev/null | grep "OpenGL core profile renderer")
    case "$renderer" in
        *llvmpipe*|*softpipe*|*swr*|*[Ss]oftware*)
            export GSK_RENDERER=ngl ;;
    esac
    unset renderer
fi
