#!/bin/sh
# Absolute path is required: the shared $HOME puts the host's pip shim at
# ~/.local/bin/qutebrowser, which shadows the container's and runs an incompatible python.

# Both builds hash to the same IPC socket name, so a running host instance would
# silently swallow this launch and open a tab there instead.
if pgrep -f '\.local/apps/qutebrowser/\.venv/bin/python3 -m qutebrowser' >/dev/null 2>&1; then
    echo "qutebrowser-arch: the host (pip) qutebrowser is running and shares the IPC socket." >&2
    echo "Quit it first, or this launch will just open a tab in that instance." >&2
    exit 1
fi

# QB_MODE works around eglCreateImage returning EGL_NOT_INITIALIZED under native
# Wayland, which loses the GL context and leaves pages rendering as background only.
PRE=""
EXTRA=""
case "${QB_MODE:-xwayland}" in
    xwayland)
        # XWayland cannot do fractional scaling, so Hyprland upscales a 1x buffer and
        # blurs it. Needs `xwayland { force_zero_scaling = true }` in hyprland.conf to help.
        SCALE=$(hyprctl monitors -j 2>/dev/null | grep -m1 '"scale"' | tr -dc '0-9.' )
        PRE="QT_QPA_PLATFORM=xcb QT_SCALE_FACTOR=${SCALE:-1}"
        ;;
    software) EXTRA="--qt-flag disable-gpu" ;;
    wayland)  ;;
    *) echo "qutebrowser-arch: unknown QB_MODE '$QB_MODE' (wayland|xwayland|software)" >&2; exit 1 ;;
esac

exec "$HOME/.local/bin/distrobox" enter --no-tty --name arch -- sh -c \
    "$PRE exec /usr/bin/qutebrowser $EXTRA \"\$@\"" -- "$@"
