#!/bin/sh -e
#
# wayland_or_x11 - determine if wayland or x11 session exists

isX() {
  echo X11
  exit
}
isW() {
  echo wayland
  exit
}

# shellcheck disable=SC2154
# Note: this is often unset for same reason above
#       when launching sway from tty
[ -e "${XDG_SESSION_ID}" ] && isW

# sometimes this works, depends on bin names and paths
pgrep -f wayland-session >/dev/null && isW

# as shitty as this is, seems to be the most effective
# although it doesn't catch DEs that could be either like Gnome
# but, if using Gnome the two cases above should have caught it

for wm in kwin_wayland sway river Hypr hyprland labwc; do
  pgrep -x "${wm}" >/dev/null && isW
done

for wm in dwm xmonad i3 openbox; do
  pgrep -x "${wm}" >/dev/null && isX
done

# Note: not reliable, when starting sway from tty not a DM this reports "tty"
if command -v loginctl >/dev/null; then
  string=$(loginctl show-session "${XDG_SESSION_ID}" -p Type)
  string=${string#Type=}
  case ${string} in
    wayland)
      isW
      ;;
    *)
      isX
      ;;
  esac
fi

# if we're still here, undeterminable
echo UNKNOWN
