#!/usr/bin/sh
set -eu
prefix=/usr/lib64/winshell/kf6
real="$prefix/libexec/winshell/yakuake/yakuake"
# Keep the invoking user's terminal environment free of private ABI variables.
unset LD_LIBRARY_PATH LD_PRELOAD LD_AUDIT QT_PLUGIN_PATH QT_QPA_PLATFORM_PLUGIN_PATH QML_IMPORT_PATH QML2_IMPORT_PATH QT_QPA_PLATFORM
[ -x "$real" ] || { echo "[Yakuake][ERROR] Missing private executable: $real" >&2; exit 127; }
# Qt's CLI platform plugin path takes precedence over compiled SDK paths.
# Choose the native transport; never silently start against a host Qt plugin.
case "${XDG_SESSION_TYPE:-}" in
    wayland) platform=wayland ;;
    x11) platform=xcb ;;
    *) if [ -n "${WAYLAND_DISPLAY:-}" ]; then platform=wayland; else platform=xcb; fi ;;
esac
platformdir=''
for dir in "$prefix/plugins/platforms" "$prefix/lib64/plugins/platforms" "$prefix/lib/plugins/platforms" "$prefix/lib64/qt6/plugins/platforms" "$prefix/lib/qt6/plugins/platforms"; do
    if [ "$platform" = xcb ]; then
        [ -f "$dir/libqxcb.so" ] || continue
    else
        found=0
        for plugin in "$dir"/libqwayland*.so; do
            [ -f "$plugin" ] && { found=1; break; }
        done
        [ "$found" = 1 ] || continue
    fi
    platformdir=$dir; break
done
[ -n "$platformdir" ] || { echo "[Yakuake][ERROR] Private $platform platform plugin missing under $prefix" >&2; exit 126; }
[ -r "${real%/*}/qt.conf" ] || { echo '[Yakuake][ERROR] Module qt.conf missing; reinstall winshell-yakuake' >&2; exit 126; }
if [ "${WINSHELL_YAKUAKE_DEBUG:-0}" = 1 ]; then
    echo "[Yakuake][QPA] platform=$platform directory=$platformdir executable=$real" >&2
    export QT_DEBUG_PLUGINS=1
fi
# Restore only private plugin roots after sanitizing inherited host paths.
export QT_PLUGIN_PATH="$prefix/plugins:$prefix/lib64/plugins:$prefix/lib/plugins:$prefix/lib64/qt6/plugins:$prefix/lib/qt6/plugins"
export QML_IMPORT_PATH="$prefix/qml:$prefix/lib64/qml:$prefix/lib/qml:$prefix/lib64/qt6/qml:$prefix/lib/qt6/qml"
export QML2_IMPORT_PATH="$QML_IMPORT_PATH"
export XDG_DATA_DIRS="$prefix/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
exec "$real" -platform "$platform" -platformpluginpath "$platformdir" "$@"
