#!/usr/bin/bash

set -e

die() { echo >&2 "!! $*"; exit 1; }

echo $@ >> /tmp/args

export DESKTOP_WAYLAND=true

SENTINEL_FILE="steamos-session-select"

session="${1:-gamescope}"
if ${DESKTOP_WAYLAND}; then
  session_type="wayland"
else
  session_type="x11"
fi

session_launcher=""
create_sentinel=""

# Update config sentinel
if [[ -z $SENTINEL_CREATED ]]; then
  [[ $EUID == 0 ]] && die "Running $0 as root is not allowed"

  [[ -n ${HOME+x} ]] || die "No \$HOME variable"
  config_dir="${XDG_CONF_DIR:-"$HOME/.config"}"
  session_type=$(
    cd "$HOME"
    mkdir -p "$config_dir"
    cd "$config_dir"
    if [[ -f "steamos-session-type" ]]; then
      cp steamos-session-type "$SENTINEL_FILE"
    else
      if ${DESKTOP_WAYLAND}; then
        echo "wayland" > "$SENTINEL_FILE"
      else
        echo "x11" > "$SENTINEL_FILE"
      fi
    fi
    cat "$SENTINEL_FILE"
  )

  # clear steam game desktop shortcut clutter
  DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share}
  grep -r --files-with-matches "Exec=steam steam://rungameid/" "${DATA_HOME}"/applications/ | tr '\n' '\0' | xargs -0 -I {} rm {} || true
fi

# We use "plasma" as "desktop" to hook up to SteamOS's scripts
case "$session" in
  plasma-wayland-persistent)
    session_launcher="desktop-wayland"
  ;;
  plasma-x11-persistent)
    session_launcher="desktop-x11"
  ;;
  desktop|plasma)
    if ${DESKTOP_WAYLAND}; then
      session_launcher="desktop-wayland"
    else
      session_launcher="desktop-x11"
    fi
    create_sentinel=1
  ;;
  gamescope)
    session_launcher="game-mode"
    create_sentinel=1
  ;;
  *)
    echo >&2 "!! Unrecognized session '$session'"
    exit 1
  ;;
esac

echo "Updated user selected session to $session_launcher"

# Check if /etc/nobara/decky_loader/autoupdate.conf exists
if [ ! -f /etc/nobara/decky_loader/autoupdate.conf ]; then
  if [ -f /etc/systemd/system/plugin_loader.service ]; then
    # File does not exist, proceed with stopping Decky Loader
    systemctl stop plugin_loader.service
    # Make sure no lingering Deckyloader processes
    ps aux | grep "$HOME/homebrew/plugins/" | grep -v grep | awk '{print $2}' | xargs -r kill -9
  fi
else
    # File exists, check its contents
    if ! grep -q 'disabled' /etc/nobara/decky_loader/autoupdate.conf; then
      if [ -f /etc/systemd/system/plugin_loader.service ]; then

        # Proceed with stopping Decky Loader
        systemctl stop plugin_loader.service
        # Make sure no lingering Deckyloader processes
        ps aux | grep "$HOME/homebrew/plugins/" | grep -v grep | awk '{print $2}' | xargs -r kill -9
      fi
    fi
fi

# Use $session_launcher.desktop to start the next session
mkdir -p $HOME/.config/sessionexec/
echo "$session_launcher.desktop" | tee "$HOME/.config/sessionexec/default"
sync

# switch the session now by restarting login_ng-session default session
login_ng-sessionctl restart
