#!/bin/sh
# Bring up graphical-session.target for lavtomate-desktop-agent on desktops that
# do not manage it (XFCE, MATE, LXDE, bare window managers): start
# lavtomate-graphical-session.target, which binds to it, and stop it when the
# graphical session ends. Run from XDG autostart on graphical login.

TARGET=lavtomate-graphical-session.target
ENV_VARS="DISPLAY XAUTHORITY WAYLAND_DISPLAY"

# The desktop runs graphical-session.target itself (GNOME, KDE): nothing to do
systemctl --user -q is-active graphical-session.target && exit 0
# Only for users who enabled the agent: the target also starts other user
# services wanted by graphical-session.target
systemctl --user -q is-enabled lavtomate-desktop-agent.service || exit 0

# The agent unit requires DISPLAY or WAYLAND_DISPLAY in the user manager
for var in $ENV_VARS; do
    eval "[ -n \"\${$var}\" ]" && systemctl --user import-environment "$var"
done
systemctl --user start "$TARGET" || exit 1

stop_session()
{
    # graphical-session.target does not stop by itself while the agent
    # (Requisite=) is active; stopping it stops PartOf/BindsTo units too
    systemctl --user stop graphical-session.target "$TARGET"
    systemctl --user unset-environment $ENV_VARS
    exit 0
}
trap stop_session HUP INT TERM

# Wait for logout: the session manager may signal us, or the login session
# leaves the active/online state (closing) while this script still runs
while :; do
    if [ -n "$XDG_SESSION_ID" ]; then
        state="$(loginctl show-session "$XDG_SESSION_ID" -p State --value 2>/dev/null)"
        case "$state" in
            active|online) ;;
            *) stop_session ;;
        esac
    fi
    sleep 5 &
    wait $!
done
