#!/sbin/openrc-run

description="PipeWire multimedia daemon (system mode for nestri)"

nestri_export_env

: "${NESTRI_UID:=1000}"
: "${NESTRI_USER:=nestri}"

command="/usr/bin/pipewire"
command_user="${NESTRI_USER}:${NESTRI_USER}"
command_background="yes"
pidfile="/run/pipewire/pipewire.pid"

export XDG_RUNTIME_DIR="/run/user/${NESTRI_UID}"
export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${NESTRI_UID}/bus"

depend() {
    need xdg-runtime dbus
    use dbus
}

start_pre() {
    checkpath -d -m 0755 -o "${NESTRI_USER}:${NESTRI_USER}" /run/pipewire
}

# `need pipewire` only waits for this script to return, and with
# command_background that is the moment start-stop-daemon forks -- not the
# moment PipeWire is accepting connections. With rc_parallel="YES" every
# client (wireplumber, neswire) then races the socket and a client that
# loses simply exits.
#
# dbus-session already solved exactly this for the bus socket. Same shape
# here.
start_post() {
    local i=0
    while [ ! -S "/run/user/${NESTRI_UID}/pipewire-0" ] && [ $i -lt 50 ]; do
        sleep 0.1
        i=$((i+1))
    done
    [ -S "/run/user/${NESTRI_UID}/pipewire-0" ] || {
        eerror "PipeWire socket never appeared"
        return 1
    }
}
