aboutsummaryrefslogtreecommitdiff
path: root/rigel/.config/sway/session-daemons.sh
blob: c8300e19c3233a9daa88cdd48025d60b745680c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#!/bin/bash
# session-daemons.sh — per-session supervisor for the daemons sway used to
# bare-`exec` (pipewire, pipewire-pulse, wireplumber, mako, waybar).
#
# Why: OpenRC has no user service manager and sway does not kill `exec`ed
# children when the session ends, so daemons pile up across dead sessions.
# 2026-10-27: three pipewire-pulse survivors (14:39 / 21:06 / current) held
# /run/user/$UID/pulse/native while this session's pipewire and wireplumber
# were dead, so every PA client got "Connection refused" — and waybar's
# pulseaudio module aborts the whole bar on pa_context_connect() failure,
# which is how the bar kept dying the moment a Moonlight stream started.
#
# What this script does instead:
#   1. singleton per session: flock; a reload re-runs `exec_always`, and the
#      stale instance just exits (see idle-start.sh for the same pattern);
#   2. on first start, kills EVERY leftover instance of the watched daemons
#      (fresh session start = fresh stack; no orphans of our own either);
#   3. starts the daemons in dependency order and restarts any that die
#      while the session lives — including waybar, which is exactly the
#      bar-resurrection behaviour we want (see the 2026-10-27 notes);
#   4. daemon stderr/stdout is appended to $runtime/session-daemons.log, so
#      a crash comes with its last words and a timestamp;
#   5. when the sway whose socket we captured exits, everything is torn
#      down — nothing survives into the next session.
#
# Session identity: $SWAYSOCK is `sway-ipc.<uid>.<pid>.sock`, same trick the
# veilad session launcher uses. Processes from other sessions carry a stale
# socket there in their environ; anything comm-matching without ours is a
# leftover and gets killed.

set -u
shopt -s nullglob

runtime="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
log="$runtime/session-daemons.log"
daemons=(pipewire pipewire-pulse wireplumber mako waybar ppd-switch.sh)

note() { echo "$(date '+%F %T') [$SWAYSOCK supervisor $$] $*" >>"$log"; }

# comm-matching pids (pgrep -x would also work; this avoids coalescing).
pids_of() {
    for p in /proc/[0-9]*; do
        [ -r "$p/comm" ] || continue
        [ "$(tr -d '\0' <"$p/comm" 2>/dev/null)" = "$1" ] && echo "${p##*/}"
    done
}

# Procpg name check. NOTE: this pgrep has no -q and errors out if given it,
# so never write `pgrep -qx` here — that made every check fail, and the
# supervise loop spawned a fresh waybar every cycle (2026-10-27).
running() { pgrep -x "$1" >/dev/null 2>&1; }

# --- singleton ----------------------------------------------------------------
# High fd: bash marks descriptors >=10 close-on-exec, so the daemons we spawn
# do NOT inherit the lock. With fd 9 they did — and surviving children then
# kept the lock forever, making every later supervisor exit silently
# (2026-10-27: 32 stray wireplumbers held the lock and froze the takeover).
lockfd=200
exec {lockfd}>"$runtime/session-daemons.lock"
if ! flock -n "$lockfd"; then
    note "another supervisor already holds the lock; exiting without changes"
    exit 0
fi

# --- session identity --------------------------------------------------------
sock="${SWAYSOCK:-}"
sway_pid=""
case "$sock" in
    */sway-ipc.*.sock)
        t="${sock##*/sway-ipc.}"   # "uid.pid.sock"
        t="${t#*.}"                # drop uid
        sway_pid="${t%%.*}"        # keep pid
        ;;
esac
if [ -z "$sock" ] || [ ! -S "$sock" ] || [ -z "$sway_pid" ] || [ ! -d "/proc/$sway_pid" ]; then
    echo "session-daemons.sh: no live sway session (SWAYSOCK='$sock'); refusing to start" >&2
    exit 1
fi

note "taking over the session daemons (sway pid $sway_pid)"

# --- first start: clear every leftover instance ------------------------------
# Both dead-session orphans (stale/error SWAYSOCK) and this session's own
# copies from before the takeover. Killing pipewire first releases the
# socket paths so the fresh instances can bind without unlink fights.
for d in "${daemons[@]}"; do
    for pid in $(pids_of "$d"); do
        note "stopping leftover $d (pid $pid)"
        kill "$pid" 2>/dev/null
    done
done
sleep 2
for d in "${daemons[@]}"; do
    for pid in $(pids_of "$d"); do
        note "force-killing leftover $d (pid $pid)"
        kill -9 "$pid" 2>/dev/null
    done
done
# Stale socket files from dead instances; fresh processes recreate them.
rm -f "$runtime/pipewire-0" "$runtime/pipewire-0-manager" "$runtime/pulse/native"

wait_for_socket() { # $1 socket path, 5s budget
    local i=0
    while [ "$i" -lt 50 ]; do
        [ -S "$1" ] && return 0
        i=$((i + 1))
        sleep 0.1
    done
    return 1
}

# --- start helpers ------------------------------------------------------------
start_daemon() {
    local d="$1" cmd="$d"
    # Bare names go through PATH (all the system daemons). Entries that live
    # in ~/.config/sway (ppd-switch.sh) are not on PATH, so resolve them to
    # the full file here. Note running()/pids_of()/kill below always use the
    # bare name, which is also the /proc comm — hence ppd-switch.sh must stay
    # <=15 chars.
    [ -x "$HOME/.config/sway/$d" ] && cmd="$HOME/.config/sway/$d"
    if running "$d"; then
        # Another path (e.g. the reload keybind) brought it back already.
        note "$d came back from elsewhere; not spawning a second copy"
        return 0
    fi
    note "starting $d"
    setsid "$cmd" >>"$log" 2>&1 </dev/null &
}

# --- dependency-ordered start -------------------------------------------------
# pipewire is the core; pipewire-pulse bridges PulseAudio clients onto it;
# wireplumber is the policy manager riding on the core.
start_daemon pipewire
if wait_for_socket "$runtime/pipewire-0"; then
    start_daemon pipewire-pulse
    wait_for_socket "$runtime/pulse/native" || note "pipewire-pulse socket still missing after 5s"
    start_daemon wireplumber
else
    note "pipewire-0 socket still missing after 5s; starting the rest anyway"
    for d in pipewire-pulse wireplumber mako waybar; do start_daemon "$d"; done
fi
start_daemon mako
start_daemon waybar

# --- supervision loop ---------------------------------------------------------
session_alive() {
    [ -S "$sock" ] && [ -d "/proc/$sway_pid" ]
}

while :; do
    if ! session_alive; then
        note "sway (pid $sway_pid) is gone; tearing the session daemons down"
        for d in "${daemons[@]}"; do
            for pid in $(pids_of "$d"); do
                kill "$pid" 2>/dev/null
            done
        done
        sleep 2
        for d in "${daemons[@]}"; do
            for pid in $(pids_of "$d"); do
                kill -9 "$pid" 2>/dev/null
            done
        done
        note "session daemons stopped; exiting"
        exit 0
    fi

    for d in "${daemons[@]}"; do
        if ! running "$d"; then
            note "*** $d died; restarting"
            start_daemon "$d"
        fi
    done
    sleep 2
done