#!/bin/sh
# Satellites: a network connected or disconnected, so each signed-in person's enabled satellites hear about it
# (their hooks/network-changed scripts). NetworkManager runs this as root with: $1 = interface, $2 = action.
# The scripts run as that person, never as root (runuser with a clean environment: their home, their session's
# runtime folder and message bus), and only for accounts that use satellites. The runner returns at once, so
# NetworkManager is never held up by a slow script. Not linked from pre-up.d: nothing here must delay a connection.
case "$2" in
    up|down|vpn-up|vpn-down|connectivity-change) ;;
    *) exit 0 ;;
esac
# loginctl prints "UID USER ..." per signed-in account; only the first two words are used
loginctl list-users --no-legend 2>/dev/null | while read -r uid name _rest; do
    [ "$uid" -ge 1000 ] 2>/dev/null || continue
    home=$(getent passwd "$name" | cut -d: -f6)
    [ -n "$home" ] && [ -f "$home/.config/starchaser/satellites.json" ] || continue
    # the tool is in /usr/bin from the package, or in the person's own ~/.local/bin from a checkout install; a person
    # with neither gets nothing (env can't find it; its complaint goes nowhere)
    # timeout: the runner returns at once once it has found the hooks; a stalled home folder holds no one up
    timeout 10 runuser -u "$name" -- env -i HOME="$home" USER="$name" LOGNAME="$name" LANG=C.UTF-8 \
        PATH="$home/.local/bin:/usr/local/bin:/usr/bin:/bin" XDG_RUNTIME_DIR="/run/user/$uid" \
        DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \
        starchaser satellite hook network-changed "STARCHASER_NETWORK_ACTION=$2" \
        "STARCHASER_NETWORK_DEVICE=${1:-}" "STARCHASER_NETWORK_STATE=${CONNECTIVITY_STATE:-}" \
        < /dev/null > /dev/null 2>&1
done
exit 0
