#!/bin/bash
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
PREFIX=$(dirname -- "${SCRIPT_DIR}")

OGUI_BIN=${OGUI_BIN:-"${PREFIX}/share/opengamepadui/opengamepad-ui.x86_64"}
GAMESCOPE_CMD=${GAMESCOPE_CMD:-gamescope -e -w 1920 -h 1080 -f --xwayland-count 2}

# Check to see if a URI is being sent
if [[ "$1" == ogui://* ]]; then
  if ls /run/user/${UID}/opengamepadui/opengamepadui-0 >/dev/null 2>&1; then
    echo "$1" >/run/user/${UID}/opengamepadui/opengamepadui-0
    exit 0
  fi
fi

# Launch normally if gamescope is already running
if ls /run/user/${UID}/gamescope* >/dev/null 2>&1; then
  echo "Executing: ${OGUI_BIN}" "$@"
  exec ${OGUI_BIN} "$@"
fi
echo "Executing: ${GAMESCOPE_CMD} -- ${OGUI_BIN}" "$@"
exec ${GAMESCOPE_CMD} -- "${OGUI_BIN}" "$@"
