#!/bin/bash
# /etc/rc.d/tinklasd — the AnotherOS network daemon (#551).
#
# tinklasd owns the 802.11 control plane: it is the only process that calls the
# blocking SYS_wifi_* syscalls, it holds the credentials from network.conf, it
# serves scan results and status to the desktop tray over /run/tinklasd, and it
# is the thing that RECONNECTS after an AP deauthenticates us. The kernel
# deliberately does not reconnect (wifi_link_lost(), kernel/net/mac80211.c) —
# the credentials are userland's — so before this daemon existed the link stayed
# down until a human ran `tinklas connect`.
#
# It REPLACES wifid, which is deleted from the tree. wifid was started by the
# Fasadas session launcher, which made the machine's network depend on a desktop
# coming up; this is a system service, so a headless or wifi-only box gets its
# link back too.
#
# Started AFTER network (rc runs /etc/rc.d/* in shell glob order, and `tinklasd`
# sorts after `network`) — not because it needs an address, but because a wifi
# join that races the wired DHCP is noise in the log for no gain.
#
# It never blocks the boot. A machine with no radio is an ordinary state: the
# daemon says so on its first line, serves clients that then hide the Wi-Fi UI,
# and does not spin a scanner thread.
case "$1" in
    start)
        # A missing binary exits 1 with a message rather than 0 in silence, for
        # the reason spelled out in rc.d/sshd: "not installed" and "installed
        # and broken" have to look different on the console.
        if [ ! -x /bin/tinklasd ]; then
            echo "rc: tinklasd: /bin/tinklasd missing or not executable" >&2
            exit 1
        fi
        /bin/tinklasd &
        ;;
    stop)
        # By PID from the file tinklasd writes, not by name: killall would also
        # take out an unrelated process whose name happens to match, and this
        # tree forbids killing by pattern outright.
        if [ -r /run/tinklasd.pid ]; then
            kill "$(cat /run/tinklasd.pid)" 2>/dev/null
        fi
        ;;
    *)
        echo "usage: $0 start|stop" >&2; exit 1 ;;
esac
exit 0
