#!/bin/sh -eu
#
#
# Copyright (C) 2024  Matthew Kosarek
# Copyright (C) 2024  Alan Griffiths
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Portions of this code originate from https://github.com/alebastr/sway-systemd,
# Portions of this code originate from https://github.com/miracle-wm-org/miracle-wm/blob/develop/session/usr/bin/libexec/miracle-wm-session-setup
# licensed under the MIT license. See the LICENSE.sway-systemd file for details.
#
# 1. Stop the target and unset the variables when the compositor exits.
#
# References:
#  - https://github.com/swaywm/sway/wiki#gtk-applications-take-20-seconds-to-start
#  - https://github.com/emersion/xdg-desktop-portal-wlr/wiki/systemd-user-services,-pam,-and-environment-variables
#  - https://www.freedesktop.org/software/systemd/man/systemd.special.html#graphical-session.target
#  - https://systemd.io/DESKTOP_ENVIRONMENTS/
#
export XDG_SESSION_DESKTOP="${XDG_SESSION_DESKTOP:-Miriway}"
VARIABLES="DESKTOP_SESSION XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP XDG_SESSION_TYPE DISPLAY WAYLAND_DISPLAY"
SESSION_TARGET="miriway-session.target"

# shellcheck disable=SC2086
systemctl --user stop "$SESSION_TARGET"

# stop the session target and unset the variables
systemctl --user start --job-mode=replace-irreversibly "$SESSION_SHUTDOWN_TARGET"
# shellcheck disable=SC2086
systemctl --user unset-environment $VARIABLES
