#!/bin/sh
#
# libra2-share-wifi - books over Wi-Fi, from a browser or as a network drive.
#
# The libra2-wifi and libra2-usb shape, deliberately: one process per question,
# one line per answer, a plain sentence on stderr and a non-zero status
# whenever the answer is no. The launcher runs this and reads its output, so
# anything that is not a machine-readable line has to be on stderr and anything
# that failed has to say so in the exit status.
#
#   libra2-share-wifi start    serve the books directory on the Wi-Fi address
#   libra2-share-wifi stop     stop the server this script started
#   libra2-share-wifi status   key<TAB>value lines: server, wifi, ip, url, dir
#
# WHAT DOES THE SERVING. dufs (github.com/sigoden/dufs, MIT or Apache-2.0), a
# single static binary that serves a directory with an upload page and speaks
# WebDAV. It is pinned by SHA-256 in mainline/tools/sources.lock and installed
# at ${SHARE_WIFI_SERVER} by the p1 build. docs/wifi-share.md is the survey and
# the choice. This file is a wrapper and nothing else: it decides WHERE the
# server may listen and WHAT it may do, and it does none of the serving.
#
# ------------------------------------------------------------------ THE BIND
#
# THE Wi-Fi ADDRESS, AND NOTHING ELSE. The server is started with one
# --bind, and it is the IPv4 address of ${WIFI_IFACE}. Never 0.0.0.0, which
# would be every interface this device has; and never ${USB_NET_ADDR}, which
# is the USB gadget link. The private reMarkable USB wrapper explicitly
# selects transport=usb, which instead requires a USB gadget interface (usb0
# on the Kobo and the reMarkable 1, usb1 on the reMarkable 2) and exactly
# USB_NET_ADDR.
#
# The USB link is the reason this rule is written down rather than assumed. It
# is the debug lifeline (S30libra2-usbnet): it is up on every boot, it hands
# the host a DHCP lease, and it is how ssh reaches a device with no console.
# A file server bound to it would be a write path into the reader's library
# that appears the moment a cable is plugged in, with no page opened and
# nobody asked - and on a device whose owner plugs the cable in to charge it,
# that is a door opened by charging.
#
# So: the address is read off the Wi-Fi interface by name, it is checked
# against the USB link's own address before it is used, and a start with no
# Wi-Fi address refuses. There is no flag and no configuration file that
# changes any of that.
#
# ------------------------------------------------------------ WHAT IT MAY DO
#
# Books is writable and Notes is read-only. The server sees only those two
# bind-mounted folders under a temporary root, never the rest of the card.
#
# --allow-upload and --allow-delete, which between them are PUT (drop a book
# in), MKCOL (make a folder), MOVE (rename) and DELETE (remove one), plus the
# reading and PROPFIND that need no flag at all. That is the set the round
# asks for and it is the whole set: --allow-search, --allow-symlink,
# --allow-archive and --allow-all are not passed. --allow-symlink in
# particular would let a request follow a link out of the books directory and
# read the rest of the device, which is not a thing a book drop needs.
#
# THERE IS NO PASSWORD, and that is a statement rather than an omission. This
# is a device on somebody's home network with their own books on it, the same
# trade the same feature makes on every reader that has it. Anyone already on
# the network can read and write the books directory while the switch is on,
# which is why the switch is off until it is asked for, off after a sleep, and
# off after a reboot.
#
# ------------------------------------------------------------- WHY IT HOLDS
#                                                                  THE CARD
#
# The server is started with its working directory INSIDE the books directory.
# That is not a detail: it is what makes this process visible to
# /usr/sbin/libra2-usb's holder scan, which walks /proc looking for anything
# whose cwd, root, exe, open files or mappings are on the card. A file server
# for a directory genuinely has that directory as its working directory, and
# being seen for what it is means the existing machinery stands it down before
# the card is handed to a computer and starts it again when the card comes
# back - rather than the card being unmounted underneath a running server,
# which would leave every upload landing on the empty mount point on p1.
# libra2-usb's SYSTEM_DAEMONS carries "dufs" for that, and daemon_init there
# names this script.
#
# ------------------------------------------------------------------ SLEEP
#
# /usr/sbin/pm stops it before it takes the radio down, and does not start it
# again on the way back up. Off at sleep means off: a device that came out of
# a pocket serving its owner's library would be a door nobody remembered
# leaving open.
#
# POSIX sh, busybox ash on the device.
#
# shellcheck source=/dev/null

set -u

LAYOUT="${LIBRA2_SHARE_LAYOUT:-/etc/libra2-linux/layout.conf}"

die() {
	printf 'libra2-share-wifi: %s\n' "$*" >&2
	exit 1
}

[ -f "${LAYOUT}" ] || die "no layout.conf at ${LAYOUT}"
. "${LAYOUT}"

SERVER="${LIBRA2_SHARE_SERVER:-${SHARE_WIFI_SERVER}}"
ASSETS="${LIBRA2_SHARE_ASSETS:-/usr/share/inkhub/share}"
BOOKS="${LIBRA2_SHARE_BOOKS:-${LOG_MOUNTPOINT}/${SHARE_WIFI_BOOKS_SUBDIR}}"
PORT="${LIBRA2_SHARE_PORT:-${SHARE_WIFI_PORT}}"
IFACE="${LIBRA2_SHARE_IFACE:-${WIFI_IFACE}}"
# Cable sharing is an explicit private-port opt-in. Wi-Fi keeps its original
# refusal of the USB address; neither mode may bind every interface.
TRANSPORT="${LIBRA2_SHARE_TRANSPORT:-wifi}"
case "$TRANSPORT" in
    wifi) LINK_NAME=Wi-Fi ;;
    usb) LINK_NAME=USB
        # A USB GADGET INTERFACE, BY NAME, AND NOTHING ELSE. It was the
        # literal usb0 until 18 September 2026, which is the Kobo's and the
        # reMarkable 1's; on the reMarkable 2 the cable is usb1 (the session
        # hands it down, tools/remarkable-share.sh), and the literal refused
        # every call on that board, stop included, which is what took sleep,
        # restart and power off away from the tablet: the session stops the
        # shares before it draws the face. The address check in cmd_start
        # still requires exactly USB_NET_ADDR, so this widens nothing a
        # server can bind.
        case "$IFACE" in
            usb[0-9] | usb[0-9][0-9]) ;;
            *) die "USB sharing requires the USB network interface." ;;
        esac ;;
    *) die "Unknown file sharing connection." ;;
esac
LOG_DIR="${LIBRA2_SHARE_LOG_DIR:-${LOG_MOUNTPOINT}/${LOG_SUBDIR}/log}"
LOG_FILE="${LOG_DIR}/${SHARE_WIFI_LOG_NAME}"

# The stock Kobo rootfs has no /run, only /var/run, and this script is also run
# by hand on a stock system while a build is being tested. The same choice
# S40libra2-wifi and pm make, for the same reason.
if [ -n "${LIBRA2_SHARE_RUN_DIR:-}" ]; then
	RUN_DIR="${LIBRA2_SHARE_RUN_DIR}"
elif [ -d /run ]; then
	RUN_DIR=/run
else
	RUN_DIR=/var/run
fi
PIDFILE="${RUN_DIR}/${SHARE_WIFI_PIDFILE_NAME}"
NOTES="${LIBRA2_SHARE_NOTES:-${LOG_MOUNTPOINT}/libra2-linux/notes}"
SHARE_ROOT="${RUN_DIR}/libra2-share-files"

# Only these two trees exist under the server root. Serving the whole card
# with path permissions is insufficient: dufs follows symlinks within its
# root before checking the target's permissions. Bind mounts keep private
# files outside that root, without copying books or notes and without a
# second server. Notes are a read-only bind; the Notes app's source stays RW.
cleanup_share() {
    [ ! -L "${SHARE_ROOT}" ] || return 1
    for part in Notes Books; do
        point="${SHARE_ROOT}/${part}"
        [ ! -L "${point}" ] || return 1
        if mountpoint -q "${point}"; then
            umount "${point}" || return 1
        fi
        [ ! -d "${point}" ] || rmdir "${point}" || return 1
    done
    [ ! -d "${SHARE_ROOT}" ] || rmdir "${SHARE_ROOT}" || return 1
}

prepare_share() {
    cleanup_share || die "The previous share could not be released. Close transfers and try again."
    if [ -L "${BOOKS}" ] || [ -L "${NOTES}" ] || [ -L "${SHARE_ROOT}" ]; then
        die "Books and Notes must be regular folders to share them."
    fi
    mkdir -p "${NOTES}" "${SHARE_ROOT}/Books" "${SHARE_ROOT}/Notes" ||
        die "The shared folders could not be prepared."
    if ! mount --bind "${BOOKS}" "${SHARE_ROOT}/Books" ||
       ! mount --bind "${NOTES}" "${SHARE_ROOT}/Notes" ||
       ! mount -o remount,bind,ro "${SHARE_ROOT}/Notes"; then
        cleanup_share || true
        die "Books and Notes could not be shared safely."
    fi
}


# The kernel's own table of TCP sockets, which is how a start finds out that
# the server really bound and really bound where it was told to. Overridable
# only so tests/94 can put a table of its own in front of this script; there is
# no such variable on the device.
PROC_NET_TCP="${LIBRA2_SHARE_PROC_NET_TCP:-/proc/net/tcp}"

# ---------------------------------------------------------- THE NAME (28b)
#
# While this server is running, and only while it is running, the device says
# on the local network that it is here and what it is serving. That is one
# file in avahi's services directory carrying both service types - _http._tcp
# for a browser and _webdav._tcp for Finder and Explorer - on the one port
# this server listens on.
#
# WRITTEN BY THE START AND TAKEN AWAY BY THE STOP, because a service record is
# a statement that something is answering. A record left behind by a stop
# would put this device in somebody's Finder sidebar and give them an error
# when they clicked it, which is worse than not being there at all. The three
# things that stop this server (the page's switch, a sleep, the card going to
# a computer) all run "stop", so all three take the record with them, and the
# directory is a symlink into tmpfs (br2-external/package/avahi_static) so a
# power cut cannot leave one either.
#
# THE NAME IN THE RECORD IS NOT WRITTEN HERE. The <name> element carries %h
# with replace-wildcards, which avahi substitutes with the host name it is
# publishing - and that name is read from the os-name file by
# /usr/sbin/libra2-mdns when the responder starts. The product is named in one
# file on this image and this is not it.
#
# AND THE RESPONDER IS ASKED FOR, WHICH IS ROUND 28c. A record is a file in a
# directory a running daemon watches; with no daemon it is a file. Round 28b
# wrote it either way and called that harmless, and on the bench it was not:
# the share came up, the page drew an address, and the device was in nobody's
# Finder sidebar with nothing anywhere saying why. So the start asks the helper
# for a responder when there is not one, and writes no record when it cannot
# have one.
#
# IT DOES NOT REFUSE, and that is round 14k putting back what 28c overshot
# (DEVIATIONS 442, flagged there as a regression on the day it shipped). 28c
# killed the server it had just started and returned an error, which is the
# right shape for the bind checks above - a server listening where it was not
# sent is a fault - and the wrong shape for this one. The name is a convenience
# on top of an address; the address is what the page draws and what has always
# worked. A device whose avahi will not start would have been a device that
# cannot share books at all. Now it shares them by address and says why in its
# own log.
MDNS_DAEMON_BIN="${LIBRA2_SHARE_MDNS_DAEMON:-${MDNS_DAEMON}}"
MDNS_HELPER_BIN="${LIBRA2_SHARE_MDNS_HELPER:-${MDNS_HELPER}}"
SERVICES_DIR="${LIBRA2_SHARE_SERVICES_DIR:-${MDNS_SERVICES_DIR}}"
SERVICES_STATE_DIR="${LIBRA2_SHARE_SERVICES_STATE_DIR:-${MDNS_SERVICES_STATE_DIR}}"
SERVICE_FILE="${SERVICES_DIR}/${SHARE_WIFI_SERVICE_NAME}"

TAB="$(printf '\t')"

usage() {
	cat <<'EOF'
usage: libra2-share-wifi COMMAND

  start    serve the books directory over Wi-Fi: upload, folders, rename,
           delete and WebDAV, bound to the Wi-Fi address and to nothing else.
  stop     stop the server this script started.
  status   one "key<TAB>value" line each for server, wifi, ip, url and dir.

Every command exits non-zero with a reason on stderr when it does not do what
it was asked. There is no switch file and nothing survives a reboot: the
server is off until somebody asks for it.
EOF
}

say() {
	printf '%s\n' "$*"
}

# One line in the share's own log, dated, for the things a reader is not
# standing in front of when they happen.
#
# THE SERVER'S LOG AND NOT A SECOND FILE. dufs logs every request into
# ${LOG_FILE} and cmd_start's comment says why it holds one writer: two
# descriptors on one file interleave mid-line. This is not that. It is a whole
# line appended by a separate open, which the kernel does not split, and it is
# written a handful of times in the life of a share rather than once a request.
# The alternative was a file of its own for two sentences a year.
#
# Always returns 0: this is called in condition position.
logline() {
	mkdir -p "${LOG_DIR}" 2>/dev/null || true
	printf '%s libra2-share-wifi: %s\n' "$(date '+%Y-%m-%dT%H:%M:%S')" "$*" \
		>>"${LOG_FILE}" 2>/dev/null || true
	return 0
}

# The address udhcpc gave the Wi-Fi interface, or nothing.
#
# The same sed S40libra2-wifi and /usr/sbin/libra2-wifi both use, by the
# interface's NAME rather than by taking the first address on the machine: the
# USB link always has one and it is never this one.
share_url() {
	if [ "${PORT}" = 80 ]; then printf 'http://%s/' "$1";
	else printf 'http://%s:%s/' "$1" "${PORT}"; fi
}

iface_ipv4() {
    if [ "$TRANSPORT" = usb ]; then
        [ "$(cat "/sys/class/net/${IFACE}/carrier" 2>/dev/null)" = 1 ] || return 0
    fi
	ifconfig "${IFACE}" 2>/dev/null |
		sed -n 's/.*inet addr:\([0-9][0-9.]*\).*/\1/p' | head -n 1
}

# pid_running PID - true when PID is a process that is still running.
#
# S30libra2-usbnet's own, copied for the reason S40libra2-wifi copies it: a
# directory in /proc is not enough, because a process that has been signalled
# and has gone but has not been reaped yet still has one. Those read Z in the
# State line and nothing else does.
pid_running() {
	[ -n "$1" ] || return 1
	[ -d "${PROC:-/proc}/$1" ] || return 1
	pid_state="$(awk '$1 == "State:" { print $2; exit }' \
		"${PROC:-/proc}/$1/status" 2>/dev/null || true)"
	[ "${pid_state}" != "Z" ]
}

# server_pid - the pid of the server this script started, or nothing.
#
# BY THE PIDFILE THIS SCRIPT WROTE, never by name. A killall would take out a
# dufs somebody started by hand over ssh to look at something, which is not
# this script's to stop.
server_pid() {
	[ -f "${PIDFILE}" ] || return 1
	pid="$(cat "${PIDFILE}" 2>/dev/null)"
	[ -n "${pid}" ] || return 1
	pid_running "${pid}" || return 1
	printf '%s\n' "${pid}"
	return 0
}

# A fifth of a second where busybox carries the applet and a whole one where it
# does not. Both are bounded by the try counts in layout.conf.
nap() {
	usleep 200000 2>/dev/null || sleep 1
}

# tcp_local ADDRESS PORT - the pair as ${PROC_NET_TCP} spells it.
#
# The kernel writes an IPv4 address in that file as four bytes of hex in the
# machine's own order, which on this ARM is little endian, so 192.168.1.34 is
# "2201A8C0"; and the port as four hex digits, so 80 is "0050". The whole
# field is the two joined by a colon.
tcp_local() {
	# shellcheck disable=SC2046  # the split into four fields is the point
	set -- $(printf '%s' "$1" | tr '.' ' ') "$2"
	printf '%02X%02X%02X%02X:%04X' "$4" "$3" "$2" "$1" "$5"
}

# listening_on LOCAL - true when something is in LISTEN on that pair.
#
# ${PROC_NET_TCP}'s columns are sl, local_address, rem_address, st, and 0A is
# TCP_LISTEN. A file that cannot be read is not an answer, so this says no; the
# caller checks that the file is readable before it asks, so a no from here
# always means what it says.
listening_on() {
	[ -r "${PROC_NET_TCP}" ] || return 1
	awk -v want="$1" '$4 == "0A" && $2 == want { found = 1 }
		END { exit found ? 0 : 1 }' "${PROC_NET_TCP}"
}

# mdns_reload - tell the responder to read its services again.
#
# avahi watches its services directory with inotify and would pick this up on
# its own; the reload is asked for anyway, because "it will notice" is a
# promise about a kernel facility this script cannot see the result of, and
# "-r" is the program's own word for the thing that has to happen. Silent and
# harmless when there is no responder running: -c says so first.
#
# Always returns 0. A share that worked is a share that worked, whether or not
# the network was told about it.
mdns_reload() {
	responder_running || return 0
	"${MDNS_DAEMON_BIN}" -r >/dev/null 2>&1 || true
	return 0
}

# responder_running - avahi's own answer to "am I running".
#
# "-c" reads its pidfile at its own compiled-in path and signals the process to
# be sure it is really that daemon. Asked of the program rather than of a file
# this script does not write, which is what /usr/sbin/libra2-mdns and
# /etc/init.d/S47libra2-bluetooth both do with the same question.
responder_running() {
	[ -n "${MDNS_DAEMON_BIN}" ] || return 1
	[ -x "${MDNS_DAEMON_BIN}" ] || return 1
	"${MDNS_DAEMON_BIN}" -c >/dev/null 2>&1
}

# ensure_responder - one, or no. Round 28c.
#
# The helper's start is bounded and idempotent: with the daemon already up it
# asks one question and returns. So this is cheap in the case that matters and
# it is the only thing that can put right the case that does not.
#
# A no is not fatal to a share. The caller logs it and serves by address; see
# cmd_start.
ensure_responder() {
	responder_running && return 0
	[ -n "${MDNS_HELPER_BIN}" ] || return 1
	[ -x "${MDNS_HELPER_BIN}" ] || return 1
	"${MDNS_HELPER_BIN}" start >/dev/null 2>&1 || true
	responder_running
}

# publish_service - one file, two service types, one port.
#
# Written to a neighbour and renamed, the way every other file this system
# writes is: avahi watches for both a close and a move into the directory, so
# a half written record is never read.
#
# Always returns 0. Whether there is a responder to read the record is settled
# by ensure_responder before this is called, and the caller does not call this
# at all when there is not one; what is left here is writing a file into tmpfs,
# and the only way that fails is a card or a directory that has already failed
# louder.
publish_service() {
	[ -n "${SHARE_WIFI_SERVICE_NAME}" ] || return 0
	mkdir -p "${SERVICES_STATE_DIR}" 2>/dev/null || true
	[ -d "${SERVICES_DIR}" ] || return 0
	cat >"${SERVICE_FILE}.new" 2>/dev/null <<EOF || return 0
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<!-- Written by ${0##*/} while the share is running, and removed when it
     stops. %h below is the host name the responder is publishing. -->
<service-group>
  <name replace-wildcards="yes">Books on %h</name>
  <service>
    <type>_http._tcp</type>
    <port>${PORT}</port>
  </service>
  <service>
    <type>_webdav._tcp</type>
    <port>${PORT}</port>
  </service>
</service-group>
EOF
	mv "${SERVICE_FILE}.new" "${SERVICE_FILE}" 2>/dev/null || {
		rm -f "${SERVICE_FILE}.new" 2>/dev/null
		return 0
	}
	mdns_reload
	return 0
}

# withdraw_service - and the record goes with the server. Always returns 0.
withdraw_service() {
	[ -n "${SHARE_WIFI_SERVICE_NAME}" ] || return 0
	rm -f "${SERVICE_FILE}" "${SERVICE_FILE}.new" 2>/dev/null || true
	mdns_reload
	return 0
}

# ---------------------------------------------------------------------------
# The verbs
# ---------------------------------------------------------------------------

cmd_start() {
	if pid="$(server_pid)"; then
		ip="$(iface_ipv4)"
		say "Books are already being shared at $(share_url "${ip:-?}") (dufs pid ${pid})"
		return 0
	fi
	# A stale pidfile from a server that has gone. Removed rather than
	# reported: /run is tmpfs, a reboot clears it, and the only way one
	# survives a stop is a stop that never ran.
	rm -f "${PIDFILE}"

	[ -x "${SERVER}" ] ||
		die "this device has no file server on it, so books cannot be shared over ${LINK_NAME}. (There is no executable at ${SERVER}; an image built from a clean tree with no network carries none)"

	ip="$(iface_ipv4)"
	[ -n "${ip}" ] ||
		die "${LINK_NAME} is not connected, so there is no address to serve on. Connect first and try again. (No IPv4 address on ${IFACE})"

    if [ "$TRANSPORT" = usb ]; then
        [ "$ip" = "$USB_NET_ADDR" ] || die "The USB network address is not ready. Reconnect the cable and try again."
    else
        [ "${ip}" != "${USB_NET_ADDR}" ] ||
            die "Books cannot be shared just now, and this device should be looked at. (${IFACE} is answering with ${USB_NET_ADDR}, which is the USB cable's own address, and that link is up whenever the device is plugged in to charge)"
    fi

	[ -d "${BOOKS}" ] ||
		die "there is nothing to share, because this device cannot see its books. (No directory at ${BOOKS} - is the card mounted?)"

	mkdir -p "${LOG_DIR}" 2>/dev/null ||
		die "books cannot be shared, because nothing can be written to the card. (${LOG_DIR} cannot be created - is the card mounted read only?)"

	prepare_share

	# THE WORKING DIRECTORY IS THE BOOKS DIRECTORY IS STILL THE CARD HOLDER, which is what makes this
	# server a card holder libra2-usb can see. See the header.
	#
	# Started with & and the shell's own $! written as the pid: dufs has no
	# pidfile option, and the busybox lesson from round 14i-3 is that a
	# pidfile option is worth nothing anyway on this image.
	#
	# stdin is closed and both output streams are appended to the log, so
	# nothing of this script's terminal is handed to a daemon that outlives
	# it. ONE WRITER ON ONE FILE: dufs logs every request on its stdout, so
	# --log-file is deliberately not passed - it would be a second descriptor
	# on the same file and the two would interleave mid-line.
	(
		cd "${BOOKS}" || exit 1
		set --
		[ ! -f "${ASSETS}/index.html" ] || set -- --assets "${ASSETS}"
		exec "${SERVER}" "$@" \
			--bind "${ip}" \
			--port "${PORT}" \
			--hidden ".inkhub-upload-*,.annotation-export-*,.annotation-export.lock,*.sdr,._*,.DS_Store" \
			--auth "@/Books:rw,/Notes" \
			--allow-upload \
			--allow-delete \
			"${SHARE_ROOT}"
	) </dev/null >>"${LOG_FILE}" 2>&1 &
	pid=$!
	printf '%s\n' "${pid}" >"${PIDFILE}" 2>/dev/null || {
        kill "${pid}" 2>/dev/null || true
        wait "${pid}" 2>/dev/null || true
        cleanup_share || true
		die "books cannot be shared, because this device cannot remember it started. (${PIDFILE} could not be written, so a later stop would not know what to stop)"
    }

	# THE START IS NOT BELIEVED UNTIL THE KERNEL AGREES.
	#
	# A backgrounded command reports that the fork worked and nothing else, so
	# a start that only checked for a running process would report success
	# over a server that had already exited on a taken port, and the page
	# would put an address on the glass that nothing answers. And a start that
	# only checked for a running process would never notice a server listening
	# somewhere it was not sent.
	#
	# So both are checked, up to ${SHARE_WIFI_START_TRIES} times a fifth of a
	# second apart: the process is alive, and ${PROC_NET_TCP} has a socket in
	# LISTEN on this port at this address. The second is the bind rule proved
	# from the kernel's own table rather than from the arguments this script
	# passed.
	# The table has to be readable before the answer it gives means anything.
	# Said here, once, rather than folded into `listening_on`: a start that
	# refused with "it never listened" because /proc was not mounted would be
	# a sentence about the wrong thing.
	[ -r "${PROC_NET_TCP}" ] || {
		kill "${pid}" 2>/dev/null || true
		rm -f "${PIDFILE}"
		cleanup_share || true
		die "books cannot be shared, because there is no way to check where the server bound. (${PROC_NET_TCP} cannot be read - is /proc mounted?)"
	}

	want="$(tcp_local "${ip}" "${PORT}")"
	tries=0
	bound=0
	while [ "${tries}" -lt "${SHARE_WIFI_START_TRIES}" ]; do
		nap
		if ! pid_running "${pid}"; then
			rm -f "${PIDFILE}"
			cleanup_share || true
			die "the file server would not start. (Port ${PORT} may already be taken; the log is at ${LOG_FILE})"
		fi
		if listening_on "${want}"; then
			bound=1
			break
		fi
		tries=$((tries + 1))
	done

	if [ "${bound}" -ne 1 ]; then
		kill "${pid}" 2>/dev/null || true
		rm -f "${PIDFILE}"
		cleanup_share || true
		die "the file server started and then did not answer, so nothing is being shared. (It never listened on ${ip}:${PORT}; the log is at ${LOG_FILE})"
	fi

	# AND NOWHERE ELSE. A server on 0.0.0.0 would be a server on the USB
	# cable's link as well, and the header says why that must never happen.
	# Asked of the kernel rather than trusted to the --bind that was passed.
	if listening_on "$(tcp_local 0.0.0.0 "${PORT}")"; then
		kill "${pid}" 2>/dev/null || true
		rm -f "${PIDFILE}"
		cleanup_share || true
		die "the file server would have been reachable over the USB cable as well, so nothing is being shared. (It bound every interface rather than ${ip} alone)"
	fi

	# The kernel has agreed, so the server really is answering: now, and not
	# a line earlier, the network is told about it. Round 28b.
	#
	# AND A DEVICE THAT CANNOT SAY ITS NAME STILL SHARES ITS BOOKS.
	#
	# Round 28c made this a refusal: no responder meant the server it had just
	# started was killed and the start returned an error, on the reading that
	# a share nobody can find in a sidebar is a feature that half works. That
	# went too far and it was flagged at the time (DEVIATIONS 442). The name
	# is a convenience ON TOP OF an address, and the address is the thing the
	# page draws, the thing the sentence below prints and the thing that has
	# always worked: taking the whole feature away to protect the convenience
	# costs a reader their books to save them a typed name.
	#
	# So the responder is asked for, and when there is not one the share goes
	# on by address with the reason in its own log. Nothing is published,
	# because a record in a directory nothing is watching is a file rather
	# than an announcement, and a stop would have nothing to withdraw.
	if ensure_responder; then
		publish_service
	else
		logline "sharing by address alone: this device is not answering to its name on the network (${MDNS_HELPER_BIN} could not start ${MDNS_DAEMON_BIN}), so nothing was published and the books are at $(share_url "${ip}")"
	fi

	# The ADDRESS and nothing else. The page draws this sentence under a page
	# that already says what to do with an address, and a helper repeating
	# the instructions would be the same words twice on one screen. Over ssh
	# it is still the one thing worth knowing.
	say "Books are being shared at $(share_url "${ip}")"
	return 0
}

cmd_stop() {
	if ! pid="$(server_pid)"; then
		rm -f "${PIDFILE}"
		# A record with no server behind it is the one thing worse than no
		# record, so a stop that found nothing running still clears it.
		withdraw_service
		cleanup_share || die "The shared folders are still in use. Close transfers and try again."
		say "Books are not being shared over ${LINK_NAME}"
		return 0
	fi

	kill "${pid}" 2>/dev/null || true
	waited=0
	while [ "${waited}" -lt "${SHARE_WIFI_STOP_TRIES}" ]; do
		pid_running "${pid}" || break
		nap
		waited=$((waited + 1))
	done
	if pid_running "${pid}"; then
		kill -9 "${pid}" 2>/dev/null || true
		nap
	fi
	rm -f "${PIDFILE}"

	if pid_running "${pid}"; then
		# The record stays, because it is still true: the server is up and
		# it is still answering. Round 28b.
		die "the file server would not stop, so the books are still being shared. (Pid ${pid} did not go; the log is at ${LOG_FILE})"
	fi
	withdraw_service
	cleanup_share || die "The shared folders are still in use. Close transfers and try again."
	say "Books are no longer being shared over ${LINK_NAME}"
	return 0
}

cmd_status() {
	if [ ! -x "${SERVER}" ]; then
		# Absent is not stopped, and the page has a different sentence for
		# it. Everything else is still answered, because a reader on a
		# device that cannot do this is still owed the truth about the
		# radio.
		printf 'server%sabsent\n' "${TAB}"
	elif server_pid >/dev/null; then
		printf 'server%srunning\n' "${TAB}"
	else
		printf 'server%sstopped\n' "${TAB}"
	fi

	ip="$(iface_ipv4)"
	if [ -n "${ip}" ]; then
		printf 'wifi%sup\n' "${TAB}"
		printf 'ip%s%s\n' "${TAB}" "${ip}"
		printf 'url%s%s\n' "${TAB}" "$(share_url "${ip}")"
	else
		printf 'wifi%sdown\n' "${TAB}"
		printf 'ip%s-\n' "${TAB}"
		printf 'url%s-\n' "${TAB}"
	fi
	printf 'dir%s%s\n' "${TAB}" "${BOOKS}"
	return 0
}

# ---------------------------------------------------------------------------

cmd="${1:-}"
[ $# -gt 0 ] && shift

case "${cmd}" in
start) cmd_start ;;
stop) cmd_stop ;;
status) cmd_status ;;
-h | --help | help)
	usage
	;;
'')
	usage >&2
	exit 1
	;;
*)
	printf 'libra2-share-wifi: no such command: %s\n' "${cmd}" >&2
	usage >&2
	exit 1
	;;
esac
