#!/usr/bin/env bash

set -e

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

SENTINEL_FILE="gamescope-session-type"

# Determine the configuration directory
if [[ "$USER" == "root" ]] ; then
  config_dir="${XDG_CONF_DIR:-"/home/$4/.config"}"
else
  config_dir="${XDG_CONF_DIR:-"$HOME/.config"}"
fi

[[ -f "$config_dir/$SENTINEL_FILE" ]] && source "$config_dir/$SENTINEL_FILE"

session="${1:-gamescope}"
session_launcher=""
create_sentinel=""

if [[ "$2" == "--sentinel-created" ]]; then
  SENTINEL_CREATED=1
fi

# Ensure necessary environment variables are set
if [[ -z "$HOME" ]]; then
  die "No \$HOME variable"
fi

update_config_sentinel() {
  [[ $EUID == 0 ]] && die "Running $0 as root is not allowed"
  mkdir -p "$config_dir"

  if [[ ! -f "$config_dir/$SENTINEL_FILE" ]]; then
    if [[ "$XDG_SESSION_TYPE" == "wayland" ]]; then
      echo "SESSION_TYPE=wayland" > "$config_dir/$SENTINEL_FILE"
    else
      echo "SESSION_TYPE=x11" > "$config_dir/$SENTINEL_FILE"
    fi
    echo "DE=$XDG_CURRENT_DESKTOP" >> "$config_dir/$SENTINEL_FILE"
  fi
}

configure_lightdm() {
  sed -i "s/^.*autologin-user=.*/autologin-user=${USER}/" /etc/lightdm/lightdm.conf.d/10-gamescope-session.conf
  sed -i "s/^.*autologin-user-timeout=.*/autologin-user-timeout=0/" /etc/lightdm/lightdm.conf.d/10-gamescope-session.conf
  sed -i "s/^.*autologin-session=.*/autologin-session=$session_launcher/" /etc/lightdm/lightdm.conf.d/10-gamescope-session.conf
  systemctl restart lightdm
}

configure_sddm() {
  sed -i "s/^.*Relogin=.*/Relogin=true/" /etc/sddm.conf.d/10-gamescope-session.conf
  sed -i "s/^.*Session=.*/Session=$session_launcher/" /etc/sddm.conf.d/10-gamescope-session.conf
  sed -i "s/^.*User=.*/User=${USER}/" /etc/sddm.conf.d/10-gamescope-session.conf
  systemctl restart sddm
}

yad_question() {
  env GDK_BACKEND="x11" yad --window-icon="/usr/share/icons/hicolor/scalable/actions/steamdeck-gaming-return.svg" --image="/usr/share/icons/hicolor/scalable/actions/steamdeck-gaming-return.svg" --question --title="$1" --text="$2" --width=300 --text-align=center
  [[ "$?" != 0 ]] && return 1 || return 0
}

if [[ -z $SENTINEL_CREATED ]]; then
  update_config_sentinel
  export SENTINEL_CREATED=1
fi

KDE_VERSION=$(grep -E '^X-KDE-PluginInfo-Version=' /usr/share/xsessions/plasmax11.desktop 2>/dev/null | cut -d'=' -f2)
if [[ "$KDE_VERSION" =~ ^6\..* ]]; then
  KDE6="true"
fi

case "$session" in
  plasma-wayland-persistent)
    if [[ "$DE" == "GNOME" ]]; then
      session_launcher="gnome-wayland"
    elif [[ "$DE" == "KDE" ]]; then
      session_launcher="plasma"
      [[ "$KDE6" != "true" ]] && session_launcher="plasmawayland"
    elif [[ "$DE" == "Hyprland" ]]; then
      session_launcher="hyprland"
    elif [[ "$DE" == "XFCE" ]]; then
      session_launcher="xfce-wayland"
    fi
    ;;
  plasma-x11-persistent)
    if [[ "$DE" == "GNOME" ]]; then
      session_launcher="gnome-xorg"
    elif [[ "$DE" == "KDE" ]]; then
      session_launcher="plasmax11"
      [[ "$KDE6" != "true" ]] && session_launcher="plasma"
    elif [[ "$DE" == "MATE" ]]; then
      session_launcher="mate"
    elif [[ "$DE" == "XFCE" ]]; then
      session_launcher="xfce"
    fi
    ;;
  desktop|plasma)
    if [[ "$SESSION_TYPE" == "wayland" ]]; then
      if [[ "$DE" == "GNOME" ]]; then
        session_launcher="gnome-wayland"
      elif [[ "$DE" == "KDE" ]]; then
        session_launcher="plasma"
        [[ "$KDE6" != "true" ]] && session_launcher="plasmawayland"
      elif [[ "$DE" == "Hyprland" ]]; then
        session_launcher="hyprland"
      elif [[ "$DE" == "XFCE" ]]; then
        session_launcher="xfce-wayland"
      fi
    else
      if [[ "$DE" == "GNOME" ]]; then
        session_launcher="gnome-xorg"
      elif [[ "$DE" == "KDE" ]]; then
        session_launcher="plasmax11"
        [[ "$KDE6" != "true" ]] && session_launcher="plasma"
      elif [[ "$DE" == "MATE" ]]; then
        session_launcher="mate"
      elif [[ "$DE" == "XFCE" ]]; then
        session_launcher="xfce"
      fi
    fi
    create_sentinel=1
    ;;
  gamescope)
    session_launcher="gamescope-session-steam"
    create_sentinel=1
    ;;
  *)
    die "Unrecognized session '$session'"
    ;;
esac

echo "Updated user selected session to $session_launcher"

if [[ ! -z $4 ]]; then
  USER="$4"
fi

if systemctl is-active --quiet gdm; then
  env GDK_BACKEND="x11" yad --window-icon="/usr/share/icons/hicolor/scalable/actions/steamdeck-gaming-return.svg" --image="/usr/share/icons/hicolor/scalable/actions/steamdeck-gaming-return.svg" --title="Требуется подтверждение" --text="Для работы данной функции требуется LIGHTDM или SDDM, GDM не поддерживается" --width=290 --text-align=center --button="OK"
  if [[ -f "$config_dir/$SENTINEL_FILE" ]]; then
    if grep -iq "autologin" "$config_dir/$SENTINEL_FILE"; then
      if ! grep -q "autologin=false" "$config_dir/$SENTINEL_FILE"; then
        sed -i 's/autologin=.*/autologin=false/' "$config_dir/$SENTINEL_FILE"
        echo "autologin set to false"
      else
        echo "autologin already set to false"
      fi
    else
      echo "autologin=false" >> "$config_dir/$SENTINEL_FILE"
      echo "autologin added as false"
    fi
  fi
  die "Autologin configuration aborted due to GDM."
fi

if [[ -f "$config_dir/$SENTINEL_FILE" ]] && ! grep -iq "autologin" "$config_dir/$SENTINEL_FILE"; then
  if [[ "$2" == "plasma" || "$2" == "desktop" ]]; then
    if yad_question "Требуется подтверждение" "Для работы данной функции требуется настроить автологин. Хотите ли вы, чтобы это было настроено автоматически?"; then
      echo "autologin=true" >> "$config_dir/$SENTINEL_FILE"
      echo "autologin enabled"
    else
      echo "autologin=false" >> "$config_dir/$SENTINEL_FILE"
      echo "autologin disabled"
    fi
  fi
fi

[[ -f "$config_dir/$SENTINEL_FILE" ]] && source "$config_dir/$SENTINEL_FILE"

if [[ "$autologin" == "true" ]] ; then
  # Re-execute as root
  if [[ $EUID != 0 ]]; then
    exec pkexec "$(realpath $0)" "$session" --sentinel-created "$session_type" "$USER"
    exit 1
  fi

  if ! grep -q "nopasswdlogin" "/etc/group" ; then
    groupadd -r nopasswdlogin
  fi

  if ! id -nG "$USER" | grep -qw "nopasswdlogin"; then
    gpasswd -a "$USER" nopasswdlogin
  fi

  if systemctl is-active --quiet lightdm; then
    configure_lightdm
  fi

  if systemctl is-active --quiet sddm; then
    configure_sddm
  fi
fi
