#!/bin/sh
set -eu

export XDG_CURRENT_DESKTOP=Wayfire:wlroots
export XDG_SESSION_DESKTOP=wayfire
export XDG_SESSION_TYPE=wayland

dbus-update-activation-environment --systemd DISPLAY WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP XDG_SESSION_TYPE 2>/dev/null || true
systemctl --user import-environment DISPLAY WAYLAND_DISPLAY XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP XDG_SESSION_TYPE 2>/dev/null || true

runtime=${XDG_RUNTIME_DIR:-/tmp}/catos-wayfire
mkdir -p "$runtime"
chmod 700 "$runtime"

run_once() {
    name=$1
    shift
    command -v "$1" >/dev/null 2>&1 || return 0
    pidfile="$runtime/$name.pid"
    if [ -r "$pidfile" ]; then
        pid=$(cat "$pidfile" 2>/dev/null || true)
        if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
            return 0
        fi
    fi
    "$@" >/dev/null 2>&1 &
    echo $! > "$pidfile"
}

run_once network nm-applet --indicator
run_once bluetooth blueman-applet
run_once polkit /usr/lib/polkit-gnome/polkit-gnome-authentication-agent-1
run_once idle swayidle -w     timeout 300 'swaylock -f -c 1f2430'     timeout 600 'wlopm --off "*"'     resume 'wlopm --on "*"'     before-sleep 'swaylock -f -c 1f2430'
