#!/bin/sh
#
# libra2-opds - fetch a catalogue's feed, and fetch a book out of one.
#
# The libra2-weather and libra2-update shape: the launcher does not open a
# socket, does not link a TLS library and does not compose an HTTP request. It
# knows what a feed means and this knows how to go and get one.
#
#   libra2-opds fetch URL FILE            write the feed at URL to FILE
#   libra2-opds download URL FILE [SIZE]  write the book at URL to FILE
#
# Both print machine-readable lines on stdout and plain sentences on stderr,
# and both exit non-zero whenever the answer is no. A sentence is for a reader
# and reaches the glass as it stands; a line is for the launcher.
#
#   fetch     bytes<TAB>N               how big the feed turned out to be
#   download  progress<TAB>SOFAR<TAB>TOTAL   while it runs, when the number moves
#             done<TAB>N                when it has landed
#
# TOTAL is "-" when nobody said how big the file is, which is most of them:
# OPDS puts a `length` on an acquisition link and only some catalogues write
# one. A percentage of a guess would be a percentage that is wrong at the end,
# so the launcher says a byte count instead when there is no total.
#
# ------------------------------------------------------------ WHERE IT WRITES
#
# Nowhere of its own. Both verbs are given a destination and both write
# "${FILE}.part" and rename it into place, which is the rule libra2-weather and
# libra2-powerd already keep: a reader must never be able to catch half a file,
# and half a book on the card is a book My Library would list and the reader
# could not open.
#
# ------------------------------------------------------------------- .local
#
# Round 28b. musl's resolver speaks DNS, and a ".local" name is not DNS: it is
# a question asked over multicast and answered by whichever machine holds the
# name. /usr/sbin/libra2-resolve asks avahi, and curl's own --resolve is how
# curl is TOLD an answer rather than made to look one up. This matters here
# rather than in theory: a reader's own calibre server is exactly such a name,
# and it is the catalogue they most want on this page. On an image with no
# resolver the fetch REFUSES and names the missing file, rather than handing
# the name to a resolver that cannot answer it and reporting a timeout.
#
# --------------------------------------------------------------- USER AGENT
#
# A user agent of our own is sent, and this is a finding rather than a
# courtesy. MEASURED 5 September 2026: gallica.bnf.fr - one of the five
# catalogues this device ships - answers 403 to a request whose User-Agent
# begins "curl/" and 200 to the same request with any other agent, curl's own
# --user-agent "-" included. So a fetcher that sent curl's default would ship
# with one of its five catalogues broken for a reason nobody could see from the
# device. The agent is built from the one file the product is named in, so a
# rename does not leave a stale string here.
#
# POSIX sh, busybox ash on the device.
#
# shellcheck source=/dev/null

set -u

PROG=libra2-opds

say() {
	printf '%s: %s\n' "${PROG}" "$*" >&2
}

die() {
	say "$*"
	exit 1
}

# Everything this script reads from the system, overridable from the
# environment for the reason libra2-weather's are: it is what lets
# tests/95-opds.sh drive the whole thing against a tree it built itself, with a
# stubbed curl, and assert what it does. None of these overrides exists on the
# device.
LAYOUT="${LIBRA2_OPDS_LAYOUT:-/etc/libra2-linux/layout.conf}"
ROUTE="${LIBRA2_OPDS_ROUTE:-/proc/net/route}"
CURL="${LIBRA2_OPDS_CURL:-curl}"

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

RESOLVE="${LIBRA2_OPDS_RESOLVE:-${OPDS_RESOLVER}}"
NAME_FILE="${LIBRA2_OPDS_NAME_FILE:-${OPDS_NAME_FILE}}"
FEED_TIMEOUT="${LIBRA2_OPDS_FEED_TIMEOUT:-${OPDS_FEED_TIMEOUT_SECONDS}}"
FEED_MAX="${LIBRA2_OPDS_FEED_MAX:-${OPDS_FEED_MAX_BYTES}}"
CONNECT_TIMEOUT="${LIBRA2_OPDS_CONNECT_TIMEOUT:-${OPDS_CONNECT_TIMEOUT_SECONDS}}"
STALL_BYTES="${LIBRA2_OPDS_STALL_BYTES:-${OPDS_STALL_BYTES_PER_SECOND}}"
STALL_SECONDS="${LIBRA2_OPDS_STALL_SECONDS:-${OPDS_STALL_SECONDS}}"
PROGRESS_SECONDS="${LIBRA2_OPDS_PROGRESS_SECONDS:-${OPDS_PROGRESS_SECONDS}}"

# THE TRUST STORE, NAMED HERE BECAUSE CURL DOES NOT KNOW WHERE IT IS.
#
# The whole of libra2-weather's note applies word for word: Buildroot's
# libcurl.mk leaves CURL_CA_BUNDLE, CURL_CA_PATH and CURL_CA_FALLBACK all
# #undef on the mbedtls branch, so a curl on this rootfs has no default trust
# store and every https fetch fails with a certificate error. The cure
# everybody reaches for is --insecure, which is a fetcher that will take a
# captive portal's certificate for standardebooks.org. So the bundle is named,
# and a device without one refuses rather than fetching without it.
CA_BUNDLE="${LIBRA2_OPDS_CA_BUNDLE:-/etc/ssl/certs/ca-certificates.crt}"

usage() {
	cat <<'EOF'
usage: libra2-opds fetch URL FILE
       libra2-opds download URL FILE [SIZE]

fetch writes the catalogue feed at URL to FILE and prints "bytes<TAB>N".
download writes the book at URL to FILE, printing "progress<TAB>SOFAR<TAB>TOTAL"
as it goes and "done<TAB>N" at the end. SIZE is what the catalogue said the
file weighs, or is left out when it said nothing.
EOF
}

# The agent this device introduces itself as.
#
# The product's own name, lower cased, out of the one file it is written in. An
# unreadable file is not a failure: the project's name is a true thing to say
# and is better than curl's default, which one of the five catalogues refuses.
user_agent() {
	ua_name=""
	if [ -r "${NAME_FILE}" ]; then
		ua_name="$(tr -d '\r\n' <"${NAME_FILE}" | tr '[:upper:]' '[:lower:]' | tr -d ' ')"
	fi
	[ -n "${ua_name}" ] || ua_name="libra2-linux"
	printf '%s/1.0\n' "${ua_name}"
}

# Is there anywhere to send a packet?
#
# libra2-weather's own, and /proc/net/route rather than `ip route` for its
# reason: busybox's ip applet is not built into this image and this file is two
# lines of text that is always there.
# EVERY VARIABLE IN HERE IS PREFIXED, and that is not a style note. POSIX sh
# has no locals, so a `read -r iface dest ...` in a helper overwrites the
# caller's `dest` - which is where the book was going. Measured: it wrote a
# reader's book to a file called 00000000, which is what the route table's
# destination column says.
has_default_route() {
	[ -r "${ROUTE}" ] || return 1
	while read -r hdr_iface hdr_dest _ _ _ _ _ hdr_mask _; do
		[ "${hdr_iface}" != "Iface" ] || continue
		[ "${hdr_dest}" = "00000000" ] || continue
		[ "${hdr_mask}" = "00000000" ] || continue
		return 0
	done <"${ROUTE}"
	return 1
}

# The scheme, the host and the port out of a URL. libra2-weather's own parser,
# because the two scripts are asking the same question of the same shapes.
url_scheme() {
	case "$1" in
	https://*) printf 'https\n' ;;
	http://*) printf 'http\n' ;;
	*) printf '\n' ;;
	esac
}

url_host() {
	uh_auth="${1#*://}"
	uh_auth="${uh_auth%%/*}"
	uh_auth="${uh_auth%%\?*}"
	uh_auth="${uh_auth%%#*}"
	# Anything before an @ is a user and a password, not a host.
	uh_auth="${uh_auth##*@}"
	case "${uh_auth}" in
	'['*)
		# A bracketed literal is an IPv6 address written out.
		printf '%s\n' "${uh_auth%%]*}]"
		return 0
		;;
	esac
	printf '%s\n' "${uh_auth%%:*}"
}

url_port() {
	up_auth="${1#*://}"
	up_auth="${up_auth%%/*}"
	up_auth="${up_auth%%\?*}"
	up_auth="${up_auth%%#*}"
	up_auth="${up_auth##*@}"
	case "${up_auth}" in
	'['*)
		up_rest="${up_auth#*]}"
		case "${up_rest}" in
		:*)
			printf '%s\n' "${up_rest#:}"
			return 0
			;;
		esac
		;;
	*:*)
		printf '%s\n' "${up_auth#*:}"
		return 0
		;;
	esac
	case "$1" in
	https://*) printf '443\n' ;;
	*) printf '80\n' ;;
	esac
}

# THE ARGUMENTS ARE BUILT IN THIS SHELL AND NOT IN A SUBSTITUTION, and that is
# the second thing measured rather than assumed. A `$(...)` runs in a subshell,
# and `die` inside one exits the SUBSHELL: the refusals below all printed their
# sentence and then the script fetched anyway. So these set globals and return
# non-zero, and the caller stops.
#
# CA_ARGS and RESOLVE_ARGS are unquoted where they are used, which is why every
# value in them is a scheme, a path, a host, a port or an address - none of
# which can hold a space. That is the same trade /usr/sbin/libra2-weather makes
# with its own --resolve.
CA_ARGS=""
RESOLVE_ARGS=""

# "--resolve host:port:ip" for a ".local" host, and nothing at all for every
# other kind of address.
resolve_for() {
	RESOLVE_ARGS=""
	lr_host="$(url_host "$1")"
	case "${lr_host}" in
	*.local) ;;
	*) return 0 ;;
	esac
	[ -x "${RESOLVE}" ] ||
		die "This device cannot look up ${lr_host} on the local network. (there is no resolver at ${RESOLVE})"
	lr_ip="$("${RESOLVE}" "${lr_host}" 2>&1)" ||
		die "${lr_host} could not be found on this network. (${lr_ip})"
	RESOLVE_ARGS="--resolve ${lr_host}:$(url_port "$1"):${lr_ip}"
}

# The scheme has to be one this device fetches, and https has to have a trust
# store behind it.
#
# --cacert for https and NOT for http, because a reader's own server on the
# local network has no certificate and never will.
trust_for() {
	CA_ARGS=""
	REDIRECT_PROTOCOLS="=http,https"
	ca_scheme="$(url_scheme "$1")"
	[ -n "${ca_scheme}" ] ||
		die "$1 is not an address this device can fetch. (a catalogue address begins https:// or http://)"
	[ "${ca_scheme}" = "https" ] || return 0
	# A secure catalogue must never redirect a feed or book onto cleartext.
	REDIRECT_PROTOCOLS="=https"
	[ -r "${CA_BUNDLE}" ] ||
		die "This device cannot make a secure connection, so it will not fetch from $1. (no trust store at ${CA_BUNDLE})"
	CA_ARGS="--cacert ${CA_BUNDLE}"
}

# The size of a file, or zero when there is not one yet.
size_bytes() {
	[ -f "$1" ] || {
		printf '0\n'
		return 0
	}
	wc -c <"$1" | tr -d ' '
}

# The destination has to be somewhere this script can write.
prepare_dest() {
	pd_dir="$(dirname "$1")"
	mkdir -p "${pd_dir}" ||
		die "There is nowhere to put that. (cannot create ${pd_dir})"
	[ -w "${pd_dir}" ] ||
		die "There is nowhere to put that. (${pd_dir} cannot be written to)"
}

do_fetch() {
	url="$1"
	dest="$2"

	prepare_dest "${dest}"
	has_default_route ||
		die "This device is not on a network, so no catalogue can be reached. Turn Wi-Fi on and join a network first."

	trust_for "${url}"
	resolve_for "${url}"

	# THE ONE LIMIT IN THIS FILE, and it is on the feed rather than on the
	# book. A feed is written to /var, which is a tmpfs a few megabytes big,
	# and a catalogue that answered a browse with half a gigabyte would wedge
	# the device rather than fail. A book goes on the card and has no limit
	# at all: how big a book is is the book's business.
	part="${dest}.part"
	rm -f "${part}"
	say "fetching ${url}"
	# WHAT THE SERVER SAID IS THE SENTENCE (bench, 7 September 2026). --fail
	# keeps an error page out of the feed, and its own line on stderr names
	# the status, so a catalogue that asked for a login (Standard Ebooks'
	# root feed, 401, Patrons Circle only) or that is not there any more
	# (Feedbooks, 404, now Cantook Market) is told apart from a device that
	# could not reach anything. Every one of those said "could not be reached".
	curl_err="${part}.err"
	rm -f "${curl_err}"
	# shellcheck disable=SC2086  # CA_ARGS and RESOLVE_ARGS are deliberate option lists.
	"${CURL}" --fail-with-body --silent --show-error --location \
		--proto "=http,https" --proto-redir "${REDIRECT_PROTOCOLS}" \
		--user-agent "$(user_agent)" \
		--connect-timeout "${CONNECT_TIMEOUT}" \
		${CA_ARGS} ${RESOLVE_ARGS} \
		--max-time "${FEED_TIMEOUT}" \
		--max-filesize "${FEED_MAX}" \
		--output "${part}" "${url}" 2>"${curl_err}" || {
		status="$(sed -n 's/.*returned error: \([0-9][0-9][0-9]\).*/\1/p' "${curl_err}" 2>/dev/null | head -n 1)"
		# Calibre uses HTTP 404, with this exact body, for an empty search.
		# Do not treat every 404 as empty: missing feeds must remain errors.
		case "${url}" in
		*/opds/search/*)
			if [ "${status}" = 404 ] && [ "$(cat "${part}" 2>/dev/null)" = 'No books found' ]; then
				printf '%s\n' '<feed xmlns="http://www.w3.org/2005/Atom"><title>No matching books</title></feed>' > "${part}"
				mv "${part}" "${dest}" || die 'Could not save the empty search result.'
				rm -f "${curl_err}"
				return 0
			fi ;;
		esac
		rm -f "${part}"
		cat "${curl_err}" >&2 2>/dev/null
		rm -f "${curl_err}"
		case "${status}" in
		401 | 403) die "That catalogue asks for a login before it will answer, and this device cannot give one yet. (HTTP ${status})" ;;
		404 | 410) die "There is no catalogue at that address any more. (HTTP ${status})" ;;
		5??) die "That catalogue is not answering at the moment. Try again later. (HTTP ${status})" ;;
		esac
		die "That catalogue could not be reached. Check the connection and the address, and try again."
	}
	rm -f "${curl_err}"

	[ -s "${part}" ] || {
		rm -f "${part}"
		die "That address answered with nothing at all, so there is no catalogue there."
	}
	mv "${part}" "${dest}" || {
		rm -f "${part}"
		die "The feed could not be put in place. (cannot rename ${part} to ${dest})"
	}
	printf 'bytes\t%s\n' "$(size_bytes "${dest}")"
	say "wrote $(size_bytes "${dest}") bytes to ${dest}"
}

# Print a progress line whenever the number has moved, until the download ends.
#
# EVERY ${PROGRESS_SECONDS} AND ONLY WHEN IT CHANGED. The launcher answers each
# line by redrawing one line of a page on an e-ink panel, so a line repeated
# every second for a file that has stopped moving would be a repaint a second
# for nothing.
watch_progress() {
	wp_pid="$1"
	wp_file="$2"
	wp_total="$3"
	wp_last=-1
	while kill -0 "${wp_pid}" 2>/dev/null; do
		wp_now="$(size_bytes "${wp_file}")"
		if [ "${wp_now}" != "${wp_last}" ]; then
			printf 'progress\t%s\t%s\n' "${wp_now}" "${wp_total}"
			wp_last="${wp_now}"
		fi
		sleep "${PROGRESS_SECONDS}"
	done
}

do_download() {
	url="$1"
	dest="$2"
	total="${3:--}"

	[ -e "${dest}" ] &&
		die "You already have that book. It is at ${dest}."

	prepare_dest "${dest}"
	has_default_route ||
		die "This device is not on a network, so nothing can be downloaded. Turn Wi-Fi on and join a network first."

	trust_for "${url}"
	resolve_for "${url}"

	part="${dest}.part"
	rm -f "${part}"
	say "downloading ${url}"

	# NO --max-time ON A BOOK, and that is a decision with a reason. A
	# twenty-five megabyte illustrated EPUB over a slow link is a slow
	# download and not a broken one, and a wall-clock limit would refuse the
	# reader's book for being long. What is refused is a transfer that has
	# STOPPED: --speed-limit with --speed-time fails when less than
	# ${STALL_BYTES} bytes a second have moved for ${STALL_SECONDS} seconds,
	# which is a dead connection rather than a slow one.
	# shellcheck disable=SC2086  # see the note on CA_ARGS and RESOLVE_ARGS
	"${CURL}" --fail --silent --show-error --location \
		--proto "=http,https" --proto-redir "${REDIRECT_PROTOCOLS}" \
		--user-agent "$(user_agent)" \
		--connect-timeout "${CONNECT_TIMEOUT}" \
		${CA_ARGS} ${RESOLVE_ARGS} \
		--speed-limit "${STALL_BYTES}" \
		--speed-time "${STALL_SECONDS}" \
		--output "${part}" "${url}" &
	curl_pid=$!
	watch_progress "${curl_pid}" "${part}" "${total}"
	wait "${curl_pid}" || {
		rm -f "${part}"
		die "That book could not be downloaded. Check the connection and try again."
	}

	[ -s "${part}" ] || {
		rm -f "${part}"
		die "That address answered with an empty file, so there is no book there."
	}
	mv "${part}" "${dest}" || {
		rm -f "${part}"
		die "The book could not be put in place. (cannot rename ${part} to ${dest})"
	}
	got="$(size_bytes "${dest}")"
	printf 'progress\t%s\t%s\n' "${got}" "${total}"
	printf 'done\t%s\n' "${got}"
	say "wrote ${got} bytes to ${dest}"
}

cmd="${1:-}"
# Not `[ $# -gt 0 ] && shift`: under a shell that stops on a failing AND-list
# that whole line fails when there are no arguments, and the script would exit
# before printing the usage it exists to print. libra2-weather's own note.
if [ $# -gt 0 ]; then
	shift
fi

case "${cmd}" in
fetch)
	[ $# -eq 2 ] || {
		usage >&2
		exit 1
	}
	do_fetch "$1" "$2"
	;;
download)
	# Written as an if rather than as `A && B || C`, which is not if-then-else
	# and which runs C whenever B is false whatever A said.
	if [ $# -lt 2 ] || [ $# -gt 3 ]; then
		usage >&2
		exit 1
	fi
	do_download "$1" "$2" "${3:--}"
	;;
-h | --help | help)
	usage
	;;
*)
	usage >&2
	exit 1
	;;
esac
