#!/usr/bin/bash

set -e

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

source /etc/default/desktop-wayland

SENTINEL_FILE="steamos-session-select"
if ${DESKTOP_WAYLAND}; then
  SENTINEL_VALUE="wayland"
else
  SENTINEL_VALUE="x11"
fi

# If we proceed, execute this
if ${DESKTOP_WAYLAND}; then
  CHAINED_SESSION="/usr/bin/startplasma-wayland"
else
  CHAINED_SESSION="/usr/bin/startplasma-x11"
fi

# If we decide the sentinel is consumed, execute this command instead and fail
RESTORE_SESSION=(steamos-session-select) # No arguments restores the session

# Find or check config sentinel
function check_sentinel()
{
  if [[ -z ${HOME+x} ]]; then
    echo >&2 "$0: No \$HOME variable!"
    # Rather than break we'll just launch plasma and hope for the best?
    return 0
  fi

  local config_dir="${XDG_CONF_DIR:-"$HOME/.config"}"
  (
    cd "$HOME"
    cd "$config_dir"
    sentinel_value="$(cat "$SENTINEL_FILE")"
    if [[ "$sentinel_value" == "wayland" ]]; then
      echo "/usr/bin/startplasma-wayland"
    elif [[ "$sentinel_value" == "x11" ]]; then
      echo "/usr/bin/startplasma-x11"
    else
      return 1
    fi
    rm "$SENTINEL_FILE"

  ) || return 1 # If we couldn't read the value or it wasn't what we wanted

  # Found value and removed it, we're good to continue
  return 0
}

if CONFIGURED_CHAINED_SESSION=$(check_sentinel); then
  # We found and consumed the oneshot sentinel, proceed to launch plasma
  echo >&2 "$0: Found and removed sentinel file for one-shot plasma, proceeding to launch"
  exec "$CONFIGURED_CHAINED_SESSION"
else
  echo >&2 "$0: Sentinel value not found, executing session-select to restore session"
  "${RESTORE_SESSION[@]}" || echo >&2 "$0: !! Failed to restore previous session, executing chained session"
  # Session restore should've stopped us, if it is broken at least let plasma continue to open
  exec "$CHAINED_SESSION"
fi
