#!/bin/sh
#
# libra2-sync - talk to KOReader's reading progress sync server.
#
# The libra2-opds and libra2-weather shape: the launcher and the reader do not
# open a socket, do not link a TLS library and do not compose an HTTP request.
# They know what a position MEANS and this knows how to go and get one.
#
#   libra2-sync auth              is this user name and key any good?
#   libra2-sync register FILE     make the account FILE describes
#   libra2-sync push FILE         send one book's position, from FILE
#   libra2-sync pull DOCUMENT     ask for one book's position
#
# Machine-readable lines on stdout, plain sentences on stderr, and a non-zero
# status whenever the answer is no.
#
#   status<TAB>N     the HTTP status, or 0 when nothing answered at all
#   body<TAB>JSON    whatever the server sent back, on one line, unread
#
# THE BODY IS NOT PARSED HERE. It is JSON, and a JSON parser written in ash
# would be the one thing this device must not have a bug of its own in: the
# bytes came off a network. src/kosync.rs parses it with serde_json, which is
# the same division docs/opds.md draws between /usr/sbin/libra2-opds and
# src/opds.rs.
#
# ------------------------------------------------------------- THE PROTOCOL
#
# KOReader's own, read out of plugins/kosync.koplugin/api.json and
# KOSyncClient.lua as we ship them (v2026.07.1):
#
#   POST /users/create            {"username":..., "password":<the MD5>}   201
#   GET  /users/auth              x-auth-user, x-auth-key                  200
#   PUT  /syncs/progress          the two headers and a JSON body          200
#   GET  /syncs/progress/<doc>    the two headers                          200
#
# x-auth-key IS THE MD5 OF THE PASSWORD AND NOT THE PASSWORD. KOReader's
# doLogin computes md5(password) and sends that; the password itself is never
# sent to the server by anybody. This script never sees a password at all: the
# account file it reads carries the key.
#
# ------------------------------------------------------------ THE ACCOUNT
#
# ${LIBRA2_SYNC_ACCOUNT}, and by default the launcher's own sync.conf on the
# card. Three keys are read out of it - server, username, userkey - and
# everything else in it is the launcher's.
#
# The override exists for one moment and it is the moment that matters: the
# Settings page TRIES a user name and a key that are not saved yet, against a
# file in tmpfs, and only writes the real account when the server says yes. A
# login that failed must not overwrite a login that works.
#
# ---------------------------------------------------- WHERE THE KEY IS NOT
#
# Not on the command line. The two auth headers and the URL go into a curl
# config file in tmpfs at mode 0600, and curl is pointed at it with -K, so
# nothing in /proc/<pid>/cmdline carries the key. It is removed on every exit
# path, including the ones that fail.
#
# ------------------------------------------------------------------- .local
#
# Round 28b, exactly as libra2-opds does it: musl's resolver speaks DNS and a
# ".local" name is not DNS, so /usr/sbin/libra2-resolve asks avahi and curl's
# own --resolve is how curl is TOLD an answer. koreader-sync is AGPL software
# anybody may run, and a reader running it on their own machine will call it
# something.local.
#
# POSIX sh, busybox ash on the device.
#
# shellcheck source=/dev/null

set -u

PROG=libra2-sync

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

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

LAYOUT="${LIBRA2_SYNC_LAYOUT:-/etc/libra2-linux/layout.conf}"
ROUTE="${LIBRA2_SYNC_ROUTE:-/proc/net/route}"
CURL="${LIBRA2_SYNC_CURL:-curl}"

[ -f "${LAYOUT}" ] || {
	say "no layout.conf at ${LAYOUT}"
	exit 1
}
. "${LAYOUT}"

ACCOUNT="${LIBRA2_SYNC_ACCOUNT:-${LOG_MOUNTPOINT}/${LOG_SUBDIR}/${SYNC_LAUNCHER_SUBDIR}/${SYNC_ACCOUNT_NAME}}"
RESOLVE="${LIBRA2_SYNC_RESOLVE:-${SYNC_RESOLVER}}"
NAME_FILE="${LIBRA2_SYNC_NAME_FILE:-${SYNC_NAME_FILE}}"
CONNECT_TIMEOUT="${LIBRA2_SYNC_CONNECT_TIMEOUT:-${SYNC_CONNECT_TIMEOUT_SECONDS}}"
PROGRESS_TIMEOUT="${LIBRA2_SYNC_PROGRESS_TIMEOUT:-${SYNC_PROGRESS_TIMEOUT_SECONDS}}"
AUTH_TIMEOUT="${LIBRA2_SYNC_AUTH_TIMEOUT:-${SYNC_AUTH_TIMEOUT_SECONDS}}"
BODY_MAX="${LIBRA2_SYNC_BODY_MAX:-${SYNC_BODY_MAX_BYTES}}"
DEFAULT_SERVER="${SYNC_DEFAULT_SERVER}"

# THE TRUST STORE, NAMED HERE BECAUSE CURL DOES NOT KNOW WHERE IT IS.
#
# libra2-weather's and libra2-opds's note, 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. The cure everybody reaches for is --insecure, which would take a
# captive portal's certificate for the sync server - and hand it a key. So the
# bundle is named, and a device without one refuses rather than talking without
# it. There is no --insecure anywhere in this file.
CA_BUNDLE="${LIBRA2_SYNC_CA_BUNDLE:-/etc/ssl/certs/ca-certificates.crt}"

if [ -n "${LIBRA2_SYNC_RUN_DIR:-}" ]; then
	RUN_DIR="${LIBRA2_SYNC_RUN_DIR}"
elif [ -d /run ]; then
	RUN_DIR=/run
else
	RUN_DIR=/var/run
fi
WORK="${RUN_DIR}/${SYNC_RUN_SUBDIR}"
CONFIG="${WORK}/curl.$$"
BODY="${WORK}/body.$$"

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

cleanup() {
	rm -f "${CONFIG}" "${CONFIG}.err" "${BODY}" 2>/dev/null || true
}

usage() {
	cat <<'EOF'
usage: libra2-sync auth
       libra2-sync register BODYFILE
       libra2-sync push BODYFILE
       libra2-sync pull DOCUMENT

Every verb prints "status<TAB>N" and, when the server sent one, "body<TAB>JSON"
on one line. The account - server, username and the MD5 of the password - is
read from ${LIBRA2_SYNC_ACCOUNT} or from the launcher's own sync.conf.
EOF
}

# The agent this device introduces itself as. libra2-opds's own, and for its
# reason: the product's name comes out of the one file it is written in, and an
# unreadable file falls back to the project's name rather than to curl's.
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-opds's own, /proc/net/route rather
# than `ip route` because busybox's ip applet is not built into this image.
# EVERY VARIABLE IN HERE IS PREFIXED: POSIX sh has no locals and a helper that
# reuses a caller's name silently overwrites it (docs/opds.md section 9.2).
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
}

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%%#*}"
	uh_auth="${uh_auth##*@}"
	case "${uh_auth}" in
	'['*)
		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
}

# One value out of the account file. The flat KEY=value this whole tree reads,
# first match wins, and everything after the first "=" is the value.
account_value() {
	av_key="$1"
	[ -r "${ACCOUNT}" ] || return 0
	sed -n "s/^[[:blank:]]*${av_key}[[:blank:]]*=[[:blank:]]*//p" "${ACCOUNT}" |
		head -n 1 | sed 's/[[:blank:]]*$//' | tr -d '\r'
}

# THE ARGUMENTS ARE BUILT IN THIS SHELL AND NOT IN A SUBSTITUTION. A `$(...)`
# runs in a subshell and `die` inside one exits the subshell, so a refusal
# there would print its sentence and then the request would go anyway. That is
# a real fault this tree has already had once, in libra2-opds, and it is
# written down there at length. These set globals and return.
RESOLVE_ARGS=""

resolve_for() {
	RESOLVE_ARGS=""
	lr_host="$(url_host "$1")"
	case "${lr_host}" in
	*.local) ;;
	*) return 0 ;;
	esac
	# Written as an if and not as `A && B || C`, which is not if-then-else and
	# which runs C whenever B is false whatever A said. docs/opds.md section
	# 9.2 records this tree finding that out the hard way.
	if [ ! -x "${RESOLVE}" ]; then
		say "This device cannot look up ${lr_host} on the local network. (there is no resolver at ${RESOLVE})"
		return 1
	fi
	if ! lr_ip="$("${RESOLVE}" "${lr_host}" 2>&1)"; then
		say "${lr_host} could not be found on this network. (${lr_ip})"
		return 1
	fi
	RESOLVE_ARGS="--resolve ${lr_host}:$(url_port "$1"):${lr_ip}"
	return 0
}

# A value as a curl config file needs it: inside double quotes, with backslash
# and double quote escaped. curl's own parser reads it back exactly.
quote_for_config() {
	printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
}

# The config file curl is pointed at, which is where the key lives instead of
# on the command line. Written at 0600 into tmpfs and removed on every exit.
write_config() {
	wc_url="$1"
	wc_scheme="$(url_scheme "${wc_url}")"
	[ -n "${wc_scheme}" ] || {
		say "${wc_url} is not an address this device can use. (a sync server address begins https:// or http://)"
		return 1
	}
	mkdir -p "${WORK}" 2>/dev/null || {
		say "this device has nowhere to work. (${WORK} cannot be created)"
		return 1
	}
	chmod 0700 "${WORK}" 2>/dev/null || true
	: >"${CONFIG}" || {
		say "this device has nowhere to work. (${CONFIG} cannot be written)"
		return 1
	}
	chmod 0600 "${CONFIG}" 2>/dev/null || true
	{
		printf 'url = "%s"\n' "$(quote_for_config "${wc_url}")"
		printf 'user-agent = "%s"\n' "$(quote_for_config "$(user_agent)")"
		printf 'header = "accept: %s"\n' "${SYNC_ACCEPT_HEADER}"
		if [ "${WANT_AUTH}" -eq 1 ]; then
			printf 'header = "%s: %s"\n' "${SYNC_USER_HEADER}" \
				"$(quote_for_config "${USERNAME}")"
			printf 'header = "%s: %s"\n' "${SYNC_KEY_HEADER}" \
				"$(quote_for_config "${USERKEY}")"
		fi
		# --cacert for https and NOT for http, because a reader's own sync
		# server on the local network has no certificate and never will.
		if [ "${wc_scheme}" = "https" ]; then
			printf 'cacert = "%s"\n' "$(quote_for_config "${CA_BUNDLE}")"
		fi
	} >>"${CONFIG}" || {
		say "this device has nowhere to work. (${CONFIG} could not be filled in)"
		return 1
	}
	if [ "${wc_scheme}" = "https" ] && [ ! -r "${CA_BUNDLE}" ]; then
		say "This device cannot make a secure connection, so it will not talk to ${wc_url}. (no trust store at ${CA_BUNDLE})"
		return 1
	fi
	return 0
}

# Make the request, print the two lines, and say whether the answer was yes.
#
# --fail is NOT passed, and that is the one difference from libra2-opds. A 401
# is an answer this device has words for - "that user name and password were
# not accepted" - and a 402 is "that name is taken", and both carry a body the
# server wrote for a person. With --fail curl would throw all of that away and
# report an exit code, so the status is read with --write-out instead and the
# refusal is decided here.
do_request() {
	dr_url="$1"
	dr_timeout="$2"
	shift 2

	has_default_route ||
		die "This device is not on a network, so reading progress cannot be shared. Turn Wi-Fi on and join a network first."

	write_config "${dr_url}" || {
		cleanup
		exit 1
	}
	resolve_for "${dr_url}" || {
		cleanup
		exit 1
	}

	rm -f "${BODY}"
	# CURL'S OWN STDERR GOES TO A FILE OF ITS OWN, and not into the variable
	# the status code is read out of. --write-out puts the code on stdout, so
	# folding stderr into the same stream would let one warning turn a
	# perfectly good 200 into "this device cannot read that".
	# shellcheck disable=SC2086  # RESOLVE_ARGS holds a host, a port and an address
	dr_code="$("${CURL}" --silent --show-error --location \
		--config "${CONFIG}" \
		--connect-timeout "${CONNECT_TIMEOUT}" \
		--max-time "${dr_timeout}" \
		--max-filesize "${BODY_MAX}" \
		${RESOLVE_ARGS} \
		--write-out '%{http_code}' \
		--output "${BODY}" "$@" 2>"${CONFIG}.err")"
	dr_status=$?
	dr_said="$(tr -d '\r\n' <"${CONFIG}.err" 2>/dev/null || true)"
	rm -f "${CONFIG}.err"

	if [ "${dr_status}" -ne 0 ]; then
		printf 'status%s0\n' "${TAB}"
		die "The sync server could not be reached. Check the connection and the address, and try again. (curl exit ${dr_status}: ${dr_said})"
	fi

	case "${dr_code}" in
	'' | *[!0-9]*)
		printf 'status%s0\n' "${TAB}"
		die "The sync server answered something this device cannot read. (${dr_code}${dr_said:+ ${dr_said}})"
		;;
	esac

	printf 'status%s%s\n' "${TAB}" "${dr_code}"
	if [ -s "${BODY}" ]; then
		# ONE LINE. JSON carries no raw newline inside a string, so taking
		# them out cannot change what the document says, and the caller reads
		# this a line at a time.
		printf 'body%s%s\n' "${TAB}" "$(tr -d '\r\n' <"${BODY}")"
	fi

	case "${dr_code}" in
	2*)
		cleanup
		return 0
		;;
	esac
	say "the server answered ${dr_code}"
	cleanup
	exit 1
}

# ---------------------------------------------------------------------------
# The account
# ---------------------------------------------------------------------------

SERVER=""
USERNAME=""
USERKEY=""
WANT_AUTH=0

read_account() {
	SERVER="$(account_value server)"
	USERNAME="$(account_value username)"
	USERKEY="$(account_value userkey)"
	[ -n "${SERVER}" ] || SERVER="${DEFAULT_SERVER}"
	# Trailing slashes off, so joining a path to it cannot double one up.
	while :; do
		case "${SERVER}" in
		*/)
			SERVER="${SERVER%/}"
			;;
		*) break ;;
		esac
	done
}

need_login() {
	[ -n "${USERNAME}" ] ||
		die "There is no user name for the sync server yet. Set one in Settings, Connect over Wi-Fi, Reading progress sync."
	[ -n "${USERKEY}" ] ||
		die "Nobody is logged in to the sync server yet. Log in from Settings, Connect over Wi-Fi, Reading progress sync."
}

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

cmd_auth() {
	read_account
	need_login
	WANT_AUTH=1
	do_request "${SERVER}${SYNC_PATH_AUTH}" "${AUTH_TIMEOUT}" --request GET
}

cmd_register() {
	rb_file="$1"
	[ -r "${rb_file}" ] ||
		die "There is nothing to register with. (${rb_file} cannot be read)"
	read_account
	# NO AUTH HEADERS ON A REGISTRATION, which is KOReader's own client:
	# register resets its middlewares and enables only Format.JSON and
	# GinClient. There is no account yet to authenticate as.
	WANT_AUTH=0
	do_request "${SERVER}${SYNC_PATH_REGISTER}" "${AUTH_TIMEOUT}" \
		--request POST \
		--header "content-type: application/json" \
		--data-binary "@${rb_file}"
}

cmd_push() {
	pb_file="$1"
	[ -r "${pb_file}" ] ||
		die "There is no position to send. (${pb_file} cannot be read)"
	read_account
	need_login
	WANT_AUTH=1
	do_request "${SERVER}${SYNC_PATH_PROGRESS}" "${PROGRESS_TIMEOUT}" \
		--request PUT \
		--header "content-type: application/json" \
		--data-binary "@${pb_file}"
}

cmd_pull() {
	pl_doc="$1"
	# A document key is KOReader's partialMD5: thirty-two hex characters and
	# nothing else. Checked rather than trusted, because it goes into a URL
	# path and this script must not be the thing that lets a book's name
	# become part of an address.
	case "${pl_doc}" in
	'' | *[!0-9a-f]*)
		die "That is not a document key, so nothing was asked for. (a key is thirty-two hexadecimal characters)"
		;;
	esac
	[ "${#pl_doc}" -eq 32 ] ||
		die "That is not a document key, so nothing was asked for. (a key is thirty-two hexadecimal characters, and that one is ${#pl_doc})"
	read_account
	need_login
	WANT_AUTH=1
	do_request "${SERVER}${SYNC_PATH_PROGRESS}/${pl_doc}" "${PROGRESS_TIMEOUT}" --request GET
}

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
auth)
	[ $# -eq 0 ] || {
		usage >&2
		exit 1
	}
	cmd_auth
	;;
register)
	[ $# -eq 1 ] || {
		usage >&2
		exit 1
	}
	cmd_register "$1"
	;;
push)
	[ $# -eq 1 ] || {
		usage >&2
		exit 1
	}
	cmd_push "$1"
	;;
pull)
	[ $# -eq 1 ] || {
		usage >&2
		exit 1
	}
	cmd_pull "$1"
	;;
-h | --help | help)
	usage
	;;
*)
	usage >&2
	exit 1
	;;
esac
