#!/bin/sh
#
# libra2-calibre - the wireless device connection to a calibre library.
#
# The libra2-share-wifi shape, verb for verb, because it is the same job on the
# same page: one process per question, one line per answer, a plain sentence on
# stderr and a non-zero status whenever the answer is no.
#
#   libra2-calibre start    look for calibre on the network and stay connected
#   libra2-calibre stop     stop the daemon this script started
#   libra2-calibre status   key<TAB>value lines: daemon, wifi, note, dir
#
# WHAT DOES THE TALKING. /usr/bin/libra2-calibred, a fourth binary out of the
# launcher's own crate behind the `calibre` cargo feature, exactly as the
# reader and the Files app are behind theirs. docs/calibre.md is the round and
# says why that half is Rust and this half is not: a length-prefixed JSON
# stream over a socket held open for as long as somebody is copying books is
# not a thing busybox ash has, and this is - a wrapper that decides what may
# run and where, and does none of the talking.
#
# ------------------------------------------------------------ WHICH WAY ROUND
#
# calibre LISTENS and this device CONNECTS. So there is no listening socket on
# this device at all, and the bind rule docs/wifi-share.md spends a page on has
# no server to apply to here. What it applies to instead is the BROADCAST: the
# daemon's discovery socket is bound to the IPv4 address of ${IFACE} and to
# nothing else, so nothing goes down the USB gadget link - which is up whenever
# the cable is plugged in to charge.
#
# That is why this script refuses to start with no Wi-Fi address, exactly as
# the file server does, and it is the same sentence.
#
# ------------------------------------------------------------- WHY IT HOLDS
#                                                                  THE CARD
#
# The daemon is started with its working directory INSIDE the books directory,
# for /usr/sbin/libra2-share-wifi's reason: that is what makes it visible to
# /usr/sbin/libra2-usb's holder scan, which walks /proc for anything whose cwd,
# root, exe, open files or mappings are on the card. Without it a share would
# unmount the card under a running daemon and every book calibre sent would
# land on the empty mount point on p1 and appear to work.
#
# ------------------------------------------------------------------ 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, which is the Wi-Fi share's
# own rule and for its reason: a device that came out of a pocket connected to
# somebody'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_CALIBRE_LAYOUT:-/etc/libra2-linux/layout.conf}"

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

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

DAEMON="${LIBRA2_CALIBRE_DAEMON:-${CALIBRE_DAEMON}}"
ONBOARD="${LIBRA2_CALIBRE_ONBOARD:-${LOG_MOUNTPOINT}}"
BOOKS="${LIBRA2_CALIBRE_BOOKS:-${ONBOARD}/${SHARE_WIFI_BOOKS_SUBDIR}}"
MACHINERY="${ONBOARD}/${LOG_SUBDIR}"
INDEX="${LIBRA2_CALIBRE_INDEX:-${MACHINERY}/${CALIBRE_INDEX_SUBPATH}}"
DATA="${LIBRA2_CALIBRE_DATA:-${MACHINERY}/${CALIBRE_READER_SUBDIR}}"
DRIVE="${LIBRA2_CALIBRE_DRIVE:-${MACHINERY}/${CALIBRE_LAUNCHER_SUBDIR}/${CALIBRE_DRIVE_NAME}}"
CONF="${LIBRA2_CALIBRE_CONF:-${MACHINERY}/${CALIBRE_LAUNCHER_SUBDIR}/${CALIBRE_CONF_NAME}}"
NAME_FILE="${LIBRA2_CALIBRE_NAME_FILE:-${SYNC_NAME_FILE}}"
IFACE="${LIBRA2_CALIBRE_IFACE:-${WIFI_IFACE}}"
LOG_DIR="${LIBRA2_CALIBRE_LOG_DIR:-${MACHINERY}/log}"
LOG_FILE="${LOG_DIR}/${CALIBRE_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, pm and libra2-share-wifi all make.
if [ -n "${LIBRA2_CALIBRE_RUN_DIR:-}" ]; then
	RUN_DIR="${LIBRA2_CALIBRE_RUN_DIR}"
elif [ -d /run ]; then
	RUN_DIR=/run
else
	RUN_DIR=/var/run
fi
PIDFILE="${RUN_DIR}/${CALIBRE_PIDFILE_NAME}"
STATE="${RUN_DIR}/${CALIBRE_STATE_NAME}"

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

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

  start    look for a calibre library on the network and stay connected to it,
           taking books into the books directory and reporting what is there.
  stop     stop the daemon this script started.
  status   one "key<TAB>value" line each for daemon, wifi, note 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
connection is off until somebody asks for it.
EOF
}

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

# The address udhcpc gave the Wi-Fi interface, or nothing.
#
# libra2-share-wifi's own, and 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.
iface_ipv4() {
	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: 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" ]
}

# daemon_pid - the pid of the daemon this script started, or nothing.
#
# BY THE PIDFILE THIS SCRIPT WROTE, never by name, for libra2-share-wifi's
# reason: a killall would take out one somebody started by hand over ssh to
# look at something, which is not this script's to stop.
daemon_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
}

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

cmd_start() {
	if pid="$(daemon_pid)"; then
		say "Already looking for calibre (pid ${pid})"
		return 0
	fi
	# A stale pidfile from a daemon 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}" "${STATE}"

	[ -x "${DAEMON}" ] ||
		die "this device cannot connect to calibre wirelessly. (There is no executable at ${DAEMON}; an image built from a clean tree with no launcher build carries none)"

	ip="$(iface_ipv4)"
	[ -n "${ip}" ] ||
		die "Wi-Fi is not connected, so there is nothing to look for calibre on. Turn Wi-Fi on and join a network first. (No IPv4 address on ${IFACE})"

	# THE ONE CHECK THAT IS NOT ABOUT THIS DEVICE WORKING, and it is
	# libra2-share-wifi's, word for word in its own terms: if the address read
	# off the Wi-Fi interface is the USB gadget link's, then something is wrong
	# with how the interfaces are named on this system, and this device would
	# be shouting down whatever is on the end of the cable.
	[ "${ip}" != "${USB_NET_ADDR}" ] ||
		die "calibre cannot be looked for 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)"

	mkdir -p "${BOOKS}" 2>/dev/null ||
		die "there is nowhere for calibre to put books. (${BOOKS} cannot be created - is the card mounted?)"

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

	# THE WORKING DIRECTORY IS THE BOOKS DIRECTORY, which is what makes this
	# daemon a card holder libra2-usb can see. See the header.
	#
	# Started with & and the shell's own $! written as the pid, which is
	# libra2-share-wifi's own note: a pidfile option is worth nothing on this
	# image anyway (round 14i-3).
	#
	# 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.
	(
		cd "${BOOKS}" || exit 1
		exec "${DAEMON}" \
			--books "${BOOKS}" \
			--index "${INDEX}" \
			--data "${DATA}" \
			--state "${STATE}" \
			--drive "${DRIVE}" \
			--conf "${CONF}" \
			--name "${NAME_FILE}" \
			--bind "${ip}" \
			--discovery "${CALIBRE_DISCOVERY_SECONDS}" \
			--retry "${CALIBRE_RETRY_SECONDS}" \
			--packet "${CALIBRE_PACKET_BYTES}"
	) </dev/null >>"${LOG_FILE}" 2>&1 &
	pid=$!
	printf '%s\n' "${pid}" >"${PIDFILE}" 2>/dev/null ||
		die "calibre cannot be connected to, 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 DAEMON SAYS SOMETHING.
	#
	# 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 daemon that had already exited on a bad argument, and the switch on the
	# page would go on over nothing. What is waited for is the daemon's own
	# state file, which it writes before it sends its first broadcast: that is
	# the daemon saying "I am up and this is what I am doing", which is more
	# than "the fork worked" and is exactly what the page draws.
	tries=0
	up=0
	while [ "${tries}" -lt "${CALIBRE_START_TRIES}" ]; do
		nap
		if ! pid_running "${pid}"; then
			rm -f "${PIDFILE}"
			die "the calibre connection would not start. (The log is at ${LOG_FILE})"
		fi
		if [ -s "${STATE}" ]; then
			up=1
			break
		fi
		tries=$((tries + 1))
	done

	if [ "${up}" -ne 1 ]; then
		kill "${pid}" 2>/dev/null || true
		rm -f "${PIDFILE}"
		die "the calibre connection started and then said nothing, so it has been stopped. (The log is at ${LOG_FILE})"
	fi

	say "Looking for calibre on this network"
	return 0
}

cmd_stop() {
	if ! pid="$(daemon_pid)"; then
		rm -f "${PIDFILE}" "${STATE}"
		say "Not connected to calibre"
		return 0
	fi

	kill "${pid}" 2>/dev/null || true
	waited=0
	while [ "${waited}" -lt "${CALIBRE_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
		die "the calibre connection would not stop. (Pid ${pid} did not go; the log is at ${LOG_FILE})"
	fi
	rm -f "${STATE}"
	say "No longer connected to calibre"
	return 0
}

cmd_status() {
	if [ ! -x "${DAEMON}" ]; 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 'daemon%sabsent\n' "${TAB}"
	elif daemon_pid >/dev/null; then
		printf 'daemon%srunning\n' "${TAB}"
	else
		printf 'daemon%sstopped\n' "${TAB}"
	fi

	if [ -n "$(iface_ipv4)" ]; then
		printf 'wifi%sup\n' "${TAB}"
	else
		printf 'wifi%sdown\n' "${TAB}"
	fi

	# THE DAEMON'S OWN SENTENCE, and it is the daemon's rather than this
	# script's: what it is doing changes without anybody pressing anything -
	# it finds calibre, it loses calibre, calibre ejects it - so it writes one
	# line into ${STATE} every time that changes and this reads it back.
	#
	# Only while the daemon is running. A line left behind by a daemon that has
	# gone would be the page saying "connected" over nothing, and the stop
	# above removes it for exactly that reason; this is the belt to that brace.
	note="-"
	if daemon_pid >/dev/null && [ -s "${STATE}" ]; then
		note="$(head -n 1 "${STATE}" | tr -d '\r')"
		[ -n "${note}" ] || note="-"
	fi
	printf 'note%s%s\n' "${TAB}" "${note}"
	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-calibre: no such command: %s\n' "${cmd}" >&2
	usage >&2
	exit 1
	;;
esac
