#!/bin/bash
# Qt must stay off hybris EGL: hybris eglGetDisplay hands the first
# connection's state to every later wl_display, so the second connection
# (SDL) dies with a protocol error. Software Qt keeps SDL the only EGL user.
export QT_QUICK_BACKEND=software
export QT_WAYLAND_CLIENT_BUFFER_INTEGRATION=none
# Forced, not defaulted: the mir1 session presets ubuntumirclient;wayland-egl;xcb
# and the mirclient QPA segfaults in the scenegraph
export QT_QPA_PLATFORM=wayland
export SDL_VIDEODRIVER=wayland
# SDL probes raw ALSA first and fails with EPERM; the session audio is pulse
export SDL_AUDIODRIVER=pulseaudio
export HAS_DESKTOP_ENVIRONMENT=0
export H264_DECODER_HINT=h264_mediacodec
export HEVC_DECODER_HINT=hevc_mediacodec
# Low-latency decode keys handled by the bundled libavcodec
export MEDIACODEC_LOW_LATENCY=1
export MEDIACODEC_OPERATING_RATE=32767
LIBDIR="$(dirname "$(readlink -f "$0")")/../lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null || echo aarch64-linux-gnu)/moonlight-qt"
export LD_LIBRARY_PATH="$LIBDIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
"$LIBDIR/moonlight" "$@" &
APP_PID=$!
# Hold a repowerd display-on request for the stream; the request dies with
# the holder connection so a crash cannot leak it
python3 - "$APP_PID" > /dev/null 2>&1 << 'PY' &
import os, sys, time
from gi.repository import Gio, GLib
bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
bus.call_sync("com.canonical.Unity.Screen", "/com/canonical/Unity/Screen",
              "com.canonical.Unity.Screen", "keepDisplayOn", None,
              GLib.VariantType("(i)"), 0, -1, None)
pid = int(sys.argv[1])
while True:
    try:
        os.kill(pid, 0)
    except OSError:
        break
    time.sleep(3)
PY
HOLDER=$!
wait $APP_PID
RC=$?
kill $HOLDER 2>/dev/null
exit $RC
