#!/bin/bash
# /etc/rc.d/garsasd — the system sound server (#940, started at boot since #1373).
#
# garsasd is where application identity lives: per-application volume and mute
# (remembered in <confdir>/garsas.conf), the Sound pane's per-app list, routing,
# events. libgarsas clients connect to it at /tmp/.garsas. Until this script
# existed NOTHING started it, so every client on every machine ran on the
# library's OSS fallback: sound came out — the fallback is load-bearing by
# design — and the policy layer the daemon exists for was simply absent
# (garsas_control_apps() answered -ENOTCONN, the Sound pane listed nobody).
#
# A SYSTEM service, not a session one, for the reason rc.d/tinklasd gives: the
# sound server must not depend on a desktop coming up, and it must already be
# there when the first client — the startup chime, a Win32 program, AMedia —
# connects, or that client lands on the fallback for its whole life.
#
# linger=never: garsasd's default is to exit five seconds after its last client
# leaves, which is right for a test daemon and wrong for a service started
# before any client exists. backend=oss: /dev/dsp, mixed by the kernel with any
# OSS program that never adopted libgarsas (#934). The daemon holds the device
# only while something is audible and releases it after a silent second.
#
# Shipped by the coresystem package as a base-owned setting (SETTINGS_OWNED in
# tools/coresystem_select.py), enabled by /etc/defaults/services/garsasd, so an
# installed machine gets the service with its next coresystem upgrade without
# anyone editing its rc.conf.
case "$1" in
    start)
        if [ ! -x /bin/garsasd ]; then
            echo "rc: garsasd: /bin/garsasd missing or not executable" >&2
            exit 1
        fi
        /bin/garsasd backend=oss linger=never &
        # By PID, recorded here: this tree never kills by pattern, and
        # `killall garsasd` would also take a private test daemon.
        echo $! > /run/garsasd.pid 2>/dev/null || true
        ;;
    stop)
        if [ -r /run/garsasd.pid ]; then
            kill "$(cat /run/garsasd.pid)" 2>/dev/null
            rm -f /run/garsasd.pid
        fi
        ;;
    *)
        echo "usage: $0 start|stop" >&2; exit 1 ;;
esac
exit 0
