#!/bin/bash
# gnome-session-stop - Stop GNOME session components for sysvinit systems
# Sends SIGTERM to all session processes tracked by PID files

# Use the session-specific rundir so we only touch our own PID files,
# not those of a new session that may have already started.
PIDDIR="${GNOME_SESSION_RUNDIR:-$XDG_RUNTIME_DIR}"

# Collect PIDs and send SIGTERM to all at once
# GSD daemons are stopped first (they depend on gnome-shell)
_pids=""
for pidfile in "$PIDDIR"/gsd-*.pid "$PIDDIR"/gnome-shell.pid \
               "$PIDDIR"/gnome-session-service.pid "$PIDDIR"/gnome-session-monitor.pid; do
    [ -f "$pidfile" ] || continue
    pid=$(cat "$pidfile" 2>/dev/null)
    if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
        kill "$pid" 2>/dev/null
        _pids="$_pids $pid"
    fi
    rm -f "$pidfile"
done

# Poll all together -- max 2s total wait
_retries=20
while [ "$_retries" -gt 0 ]; do
    _alive=0
    for pid in $_pids; do
        kill -0 "$pid" 2>/dev/null && _alive=1 && break
    done
    [ "$_alive" = "0" ] && break
    sleep 0.1
    _retries=$((_retries - 1))
done

# Force-kill survivors
for pid in $_pids; do
    kill -0 "$pid" 2>/dev/null && kill -9 "$pid" 2>/dev/null
done
unset _pids pid _retries _alive

# Clean up the leader FIFO
rm -f "$PIDDIR/gnome-session-leader-fifo"

# Remove the session-specific rundir entirely so nothing stale is left
if [ -n "$GNOME_SESSION_RUNDIR" ] && [ "$GNOME_SESSION_RUNDIR" != "$XDG_RUNTIME_DIR" ]; then
    rm -rf "$GNOME_SESSION_RUNDIR"
fi
