#!/bin/bash

set -e

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

SENTINEL_FILE="manjaro-session-select"
SENTINEL_VALUE="plasma-manjaro-oneshot.desktop"

# If we proceed, execute this
CHAINED_SESSION="/usr/bin/startplasma-x11"
# If we decide the sentinel is consumed, execute this command instead and fail
RESTORE_SESSION=(manjaro-session-select) # No arguments restores the session

# Find or check config sentinel
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")"
    [[ $sentinel_value = "$SENTINEL_VALUE" ]] || return 1
    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 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 "$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
