# Every BlueRune session started from now on starts bluerune-extension-weather.service itself
# (bluerune-session.target wants it). These bring along the sessions running now: the extension
# starts in them once installed, restarts on an upgrade, and stops before it is removed, which
# takes its items away.

_unit=bluerune-extension-weather.service

# _in_sessions <systemctl arguments>: runs them on the user manager of each user whose BlueRune
# session is running. Nothing in a chroot or a system that isn't booted, such as an install.
_in_sessions() {
    systemd-detect-virt --chroot >/dev/null 2>&1 && return 0
    systemd-notify --booted 2>/dev/null || return 0
    local user
    for user in $(loginctl list-users --no-legend 2>/dev/null | awk '{ print $2 }'); do
        systemctl --user -M "$user@" is-active --quiet bluerune-session.target 2>/dev/null || continue
        systemctl --user -M "$user@" "$@" >/dev/null 2>&1 || true
    done
}

post_install() {
    _in_sessions daemon-reload
    _in_sessions start --no-block "$_unit"
}

post_upgrade() {
    _in_sessions daemon-reload
    _in_sessions try-restart --no-block "$_unit"
}

pre_remove() {
    _in_sessions stop "$_unit"
}
