#!/usr/bin/env bash
set -euo pipefail
LOGFILE="$HOME/.local/logs/desktop.log"
export PATH="$HOME/.local/bin:$PATH"

log() { echo "[$(date --iso-8601=seconds)] $*" | tee -a "$LOGFILE"; }

DESKTOP_BIN="$(command -v plasmashell || true)"
if [ -z "$DESKTOP_BIN" ]; then
  log "ERROR: plasmashell not found in PATH"
  exit 127
fi

export XDG_CURRENT_DESKTOP=plasma
export XDG_CURRENT_DESKTOP=KDE

export QT_QPA_PLATFORM=wayland
export GDK_BACKEND=wayland
export CLUTTER_BACKEND=wayland
export SDL_VIDEODRIVER=wayland
export MOZ_ENABLE_WAYLAND=1
export KDEDIRS=/usr
export KDE_FULL_SESSION=true
export DESKTOP_SESSION=plasma

unset DISPLAY

mkdir -p $XDG_RUNTIME_DIR
chmod 700 $XDG_RUNTIME_DIR

log "Launching Plasma: $DESKTOP_BIN"
systemd-run --user --scope --quiet \
  --unit=plasma.scope \
  --slice=desktop.slice \
  "$DESKTOP_BIN" >>"$LOGFILE" 2>&1 &
plasma_scope_pid=$!
log "Plasma started with scope pid $plasma_scope_pid"

{
  SUNSHINE_BIN="$(command -v sunshine || true)"
  if [ -z "$SUNSHINE_BIN" ]; then
    log "ERROR: sunshine not found in PATH"
  else
    SUNSHINE_LOG_FILE="$HOME/.local/logs/sunshine.log"
    log "Found Sunshine: $SUNSHINE_BIN, starting after 5s delay"
    sleep 5
    systemd-run --user --scope --quiet \
    --unit=sunshine.scope \
    --slice=sunshine.slice \
    "$SUNSHINE_BIN" "$HOME/.config/sunshine/sunshine.conf"
  fi
} &

wait "$plasma_scope_pid"
status=$?

# Stop Sunshine gracefully
if systemctl --user is-active --quiet sunshine.scope; then
  log "Stopping Sunshine"
  systemctl --user stop sunshine.scope
fi

log "Plasma session ended."
exit "$status"