#!/bin/sh
#
# libra2-weather - the only thing on this system that fetches the weather.
#
# The launcher does not open a socket, does not link a TLS library and does not
# know a URL. It reads two files this script writes and draws what it finds.
# This is that half: fetch a forecast for the place the reader chose, or
# resolve a name they typed into a list of places to pick from.
#
#   libra2-weather fetch                the forecast, for the place in home.conf
#   libra2-weather geocode NAME         places called NAME, for the pick list
#   libra2-weather fetch --fixture F    take F as the response, ask nothing
#   libra2-weather geocode NAME --fixture F     the same, for a search
#
# --fixture IS NOT A TEST HOOK BOLTED ON. The development unit's wifi is dead
# silicon (DEVIATIONS 228) and it is the only unit this round can be flown on,
# so --fixture is how the whole chain - write the files, signal the launcher,
# repaint the cell - is exercised on hardware that cannot reach the network.
# The first live fetch happens on the working unit under round 8a. See
# DEVIATIONS.
#
# THE SOURCE is Open-Meteo: free, no account, no key, CC BY 4.0, and the
# attribution is on the Weather page. The parameter set below is transcribed
# from the owner's own github.com/juicecultus/joan-dashboard (MIT), which
# drives a Visionect e-ink dashboard from these same two endpoints. None of
# that code runs here.
#
# WHAT IT WRITES, under the launcher's state directory on p1:
#
#   weather.json    the response, RAW and unparsed
#   weather.stamp   when it was fetched, in epoch seconds, one line
#   geocode.json    the last place search, raw
#   geocode.stamp   the same, for that
#
# Raw rather than digested, on purpose: a parser here would put the shape of
# Open-Meteo's response into a shell script, and then every field added at the
# far end would need a change on both sides. This knows the URL. The launcher
# knows the payload (mainline/src/libra2-launcher2/src/weather.rs).
#
# Both are written to a .new and renamed, exactly as libra2-powerd writes the
# low-battery file and for the same reason: a reader woken by the signal must
# not be able to catch half a file.
#
# THE SIGNAL is SIGUSR1, and it is sent ONLY WHEN THE RESPONSE CHANGED. That
# condition is not tidiness. SIGUSR1 already means "the panel is not where you
# left it" (docs/apps.md section 7, DEVIATIONS 237), so the launcher answers it
# with a whole-frame repaint, which on this panel is a full flash. A fetch that
# came back with the bytes that were already on disk has nothing to show and
# must not cost one.
set -eu

PROG=libra2-weather

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

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

# Everything this script reads from the system, overridable from the
# environment for the same reason S15libra2-cpufreq's two roots are: it is what
# lets tests/52-weather.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_WEATHER_LAYOUT:-/etc/libra2-linux/layout.conf}"
STATE="${LIBRA2_WEATHER_STATE:-/var/lib/libra2/launcher}"
ROUTE="${LIBRA2_WEATHER_ROUTE:-/proc/net/route}"
PROC="${LIBRA2_WEATHER_PROC:-/proc}"
CURL="${LIBRA2_WEATHER_CURL:-curl}"
# The hourly borrow of an idled radio (see borrow_radio below).
WIFI="${LIBRA2_WEATHER_WIFI:-/usr/sbin/libra2-wifi}"
WIFI_IDLED="${LIBRA2_WEATHER_WIFI_IDLED:-/run/libra2-wifi-idled}"
BORROWED="${LIBRA2_WEATHER_BORROWED:-/run/libra2-weather-borrowed}"
IDLE_WORK="${LIBRA2_WEATHER_IDLE_WORK:-/run/libra2-idle.work}"
ROUTE_WAIT="${LIBRA2_WEATHER_ROUTE_WAIT:-30}"
BORROW_EVERY="${LIBRA2_WEATHER_BORROW_EVERY:-3300}"
RESOLVE="${LIBRA2_WEATHER_RESOLVE:-/usr/sbin/libra2-resolve}"
NOW="${LIBRA2_WEATHER_NOW:-}"

# layout.conf names the FAT mount point and the launcher's process name. It is
# sourced rather than parsed because every other script on this device sources
# it, and a second parser for one file is a second thing to get wrong.
#
# shellcheck source=/dev/null
if [ -r "${LAYOUT}" ]; then
	. "${LAYOUT}"
fi
: "${LOG_MOUNTPOINT:=/mnt/onboard}"
: "${LOG_SUBDIR:=libra2-linux}"
: "${POWER_LAUNCHER_PROCESS:=libra2-launcher2}"

# The reader's own home screen file, on the card. The place lives there rather
# than beside the forecast because it is a CHOICE and the forecast is a cache:
# see mainline/src/libra2-launcher2/src/prefs.rs, which writes it.
HOME_CONF="${LIBRA2_WEATHER_HOME:-${LOG_MOUNTPOINT}/${LOG_SUBDIR}/launcher/home.conf}"

FORECAST_URL="${LIBRA2_WEATHER_FORECAST_URL:-https://api.open-meteo.com/v1/forecast}"
GEOCODE_URL="${LIBRA2_WEATHER_GEOCODE_URL:-https://geocoding-api.open-meteo.com/v1/search}"

# How long curl gets. Twenty seconds is generous for one small JSON document
# and short enough that a crond run cannot pile up behind the next one, which
# is thirty minutes away.
TIMEOUT="${LIBRA2_WEATHER_TIMEOUT:-20}"

# THE TRUST STORE, NAMED HERE BECAUSE CURL DOES NOT KNOW WHERE IT IS.
#
# This is not belt and braces and it is not a preference. Buildroot's
# package/libcurl/libcurl.mk gives curl a default CA location for exactly three
# of its four TLS back ends: openssl gets --with-ca-path, gnutls gets
# --with-ca-fallback, wolfssl gets --with-ca-bundle. The mbedtls branch passes
# --with-mbedtls and nothing else, so the binary this rootfs builds has
# CURL_CA_BUNDLE, CURL_CA_PATH and CURL_CA_FALLBACK all left #undef (MEASURED:
# build/libcurl-8.15.0/lib/curl_config.h lines 7, 10 and 13, 2026-09-02).
#
# A curl with no trust store fails EVERY https fetch with a certificate error,
# and the cure everybody reaches for at that point is --insecure - which is a
# fetcher that will take a captive portal's certificate for
# api.open-meteo.com. So the bundle is named, explicitly, and if it is not
# there this script REFUSES rather than fetching without it.
#
# The path is ca-certificates.mk's own: it installs the concatenated bundle at
# /etc/ssl/certs/ca-certificates.crt. See DEVIATIONS.
CA_BUNDLE="${LIBRA2_WEATHER_CA_BUNDLE:-/etc/ssl/certs/ca-certificates.crt}"

# Today and five more, which is what the Weather page shows.
FORECAST_DAYS=6
# At most six places in the pick list, which is what fits above the navigation
# bar on the settings page.
GEOCODE_COUNT=6

# One KEY=value out of home.conf. Same shape as app.conf, read the same way.
conf_value() {
	[ -r "${HOME_CONF}" ] || return 0
	sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" "${HOME_CONF}" |
		sed -e 's/[[:space:]]*$//' -e '1q'
}

# Is there anywhere to send a packet?
#
# /proc/net/route rather than `ip route`: busybox's ip applet is not built into
# this image and this file is two lines of text that is always there. A default
# route is the one whose destination AND mask are both zero.
has_default_route() {
	[ -r "${ROUTE}" ] || return 1
	while read -r iface dest _ _ _ _ _ mask _; do
		[ "${iface}" != "Iface" ] || continue
		[ "${dest}" = "00000000" ] || continue
		[ "${mask}" = "00000000" ] || continue
		return 0
	done <"${ROUTE}"
	return 1
}

# The launcher's pid, by argv[0] BASENAME and never by comm.
#
# comm is TASK_COMM_LEN, sixteen bytes including the terminator, so this
# process appears there as "libra2-launcher" - fifteen characters, and a
# different program's name (MEASURED on the dev unit, /proc/185/comm,
# 2026-09-01). libra2-powerd finds it the same way; docs/apps.md section 7 is
# the contract both obey.
launcher_pid() {
	for d in "${PROC}"/[0-9]*; do
		[ -r "${d}/cmdline" ] || continue
		argv0=$(tr '\0' '\n' <"${d}/cmdline" | sed -e '1q')
		[ -n "${argv0}" ] || continue
		if [ "$(basename "${argv0}")" = "${POWER_LAUNCHER_PROCESS}" ]; then
			printf '%s\n' "${d##*/}"
			return 0
		fi
	done
	return 1
}

# "There is something new to read." Not an error when nobody is listening: the
# file is written either way and whoever starts next reads it, which is the
# rule the low-battery file already follows.
signal_launcher() {
	pid=$(launcher_pid) || {
		say "nothing to tell: no ${POWER_LAUNCHER_PROCESS} is running"
		return 0
	}
	if kill -USR1 "${pid}" 2>/dev/null; then
		say "told ${POWER_LAUNCHER_PROCESS} (pid ${pid})"
	else
		say "could not signal pid ${pid}"
	fi
}

now_seconds() {
	if [ -n "${NOW}" ]; then
		printf '%s\n' "${NOW}"
	else
		date -u +%s
	fi
}

# local_resolve_args URL - "--resolve host:port:ip" for a ".local" host.
#
# ROUND 28b, AND WHY IT IS HERE AT ALL. 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. So curl cannot look one up, and neither
# can this script. /usr/sbin/libra2-resolve asks avahi instead, and curl's own
# --resolve is how curl is TOLD an answer rather than made to find one.
#
# Prints nothing at all for every other kind of address, which is every URL
# this script has today: the two open-meteo endpoints are ordinary public
# names and this function returns before it does anything. It is here because
# the endpoints are overridable, and a reader who points this at a forecast
# service on their own network should not find that the one host name their
# machine answers to is the one this device cannot reach.
#
# The port is curl's own default for the scheme when the URL does not carry
# one, because --resolve is keyed on the port curl will actually connect to.
local_resolve_args() {
	case "$1" in
	https://*) lr_port=443 ;;
	http://*) lr_port=80 ;;
	*) return 0 ;;
	esac
	lr_auth="${1#*://}"
	lr_auth="${lr_auth%%/*}"
	lr_auth="${lr_auth%%\?*}"
	lr_auth="${lr_auth%%#*}"
	# Anything before an @ is a user and a password, not a host.
	lr_auth="${lr_auth##*@}"
	# A bracketed literal is an IPv6 address written out, so there is
	# nothing to look up and nothing here would parse it correctly either.
	case "${lr_auth}" in
	'['*) return 0 ;;
	esac
	lr_host="${lr_auth%%:*}"
	case "${lr_auth}" in
	*:*) lr_port="${lr_auth#*:}" ;;
	esac
	case "${lr_host}" in
	*.local) ;;
	*) return 0 ;;
	esac
	[ -x "${RESOLVE}" ] ||
		die "${lr_host} cannot be looked up on this device (no ${RESOLVE})"
	lr_ip="$("${RESOLVE}" "${lr_host}" 2>&1)" ||
		die "${lr_host} could not be found on this network: ${lr_ip}"
	printf -- '--resolve\n%s:%s:%s\n' "${lr_host}" "${lr_port}" "${lr_ip}"
}

# curl, with the arguments every call needs.
#
# --fail so an HTTP error is an error rather than a body; --location because
# both endpoints may redirect; --cacert because of the note above.
fetch_with_curl() {
	[ -r "${CA_BUNDLE}" ] ||
		die "no trust store at ${CA_BUNDLE} - refusing to fetch without one"
	# The status is taken, not just the words. A command substitution runs in
	# a subshell, so the die inside local_resolve_args ends the subshell and
	# nothing else; without this, a name that could not be resolved would
	# come back as an empty resolve list and curl would be sent to look the
	# name up itself, which is the one thing it cannot do.
	if ! resolve="$(local_resolve_args "$1")"; then
		return 1
	fi
	# shellcheck disable=SC2086  # empty for every ordinary URL, two words
	# for a ".local" one, and neither a host nor an address can hold a space
	"${CURL}" --fail --silent --show-error --location \
		--max-time "${TIMEOUT}" \
		--cacert "${CA_BUNDLE}" \
		${resolve} \
		--get "$@"
}

# A response is a response only if it is one.
#
# The launcher parses it properly and refuses what it cannot read, so this is
# deliberately the smallest check that catches the case worth catching here: a
# captive portal's login page, or a proxy's error page, arriving with a 200 and
# being written over a forecast that was fine. Empty, or not starting with a
# brace, and it does not become weather.json.
looks_like_json() {
	[ -s "$1" ] || return 1
	case "$(dd if="$1" bs=1 count=1 2>/dev/null)" in
	'{') return 0 ;;
	*) return 1 ;;
	esac
}

# Put a fetched body in place, and say whether it CHANGED.
#
# Returns 0 when the file on disk is now different from what was there, which
# is the condition SIGUSR1 is sent on. The stamp is written either way: the
# reading is current whether or not its bytes moved.
#
# AND WHEN NOTHING MOVED, NOTHING IS WRITTEN. cmp -s has just proved that the
# bytes on disk are the bytes we fetched, so the copy and the rename would put
# the same 17 KB back where it already is - 48 times a day on p1, for a
# forecast that mostly does not change between two half hours. The stamp still
# goes down, because the launcher reads its CONTENT rather than its mtime
# (libra2-ui/src/weather.rs age()) and freshness has to keep meaning "when we
# last asked" rather than "when it last changed".
# The body with the server's own noise taken out, for comparing and nothing
# else. Three expressions because the field has sat mid-object (the forecast),
# last (the geocoder's results) and alone (the geocoder with nothing found).
steady() {
	sed -e 's/"generationtime_ms":[^,}]*,//' \
		-e 's/,"generationtime_ms":[^,}]*//' \
		-e 's/"generationtime_ms":[^,}]*//' "$1"
}

install_body() {
	body="$1"
	name="$2"
	stamp="$3"

	mkdir -p "${STATE}" || die "cannot create ${STATE}"

	# The comparison ignores "generationtime_ms", the time the server took
	# to answer, because it differs on every request: byte for byte, two
	# identical forecasts NEVER matched, so the guard below never fired and
	# - older than the guard - SIGUSR1 and a whole-panel repaint went out
	# on every half-hour fetch since the weather card existed. The bench
	# found it on 7 September 2026 with two fetches twenty seconds apart.
	# Only the comparison ignores it: what is stored stays the response,
	# raw and byte for byte, and the launcher never reads the field.
	changed=1
	if [ -f "${STATE}/${name}" ] &&
		[ "$(steady "${body}")" = "$(steady "${STATE}/${name}")" ]; then
		changed=0
	fi

	if [ "${changed}" -eq 1 ]; then
		cp "${body}" "${STATE}/${name}.new" || die "cannot write ${STATE}/${name}.new"
		mv "${STATE}/${name}.new" "${STATE}/${name}" || die "cannot replace ${STATE}/${name}"
	fi

	now_seconds >"${STATE}/${stamp}.new" || die "cannot write ${STATE}/${stamp}.new"
	mv "${STATE}/${stamp}.new" "${STATE}/${stamp}" || die "cannot replace ${STATE}/${stamp}"

	[ "${changed}" -eq 1 ]
}

# --- THE HOURLY BORROW (23 September 2026) ---------------------------------
#
# With the radio idled off between uses (powerd's transparent idle), there is
# no route and the half-hourly crond run below asked nothing, so the weather
# froze. Justin asked for it to keep updating hourly while the device is in
# use. crond only runs while the device is awake, so this never wakes it; it
# borrows a radio that idle-off took down (libra2-wifi borrow refuses anything
# else, a reader's own Wi-Fi off included), at most once an hour, waits for a
# route, fetches, and gives the radio back with idle-off. While it works it
# holds the idle work lock shared, as the launcher's own work does, so a
# sleep behind the screen cannot freeze the download halfway.
#
# Cost, estimated: 10 to 15 s of radio at 100 to 150 mA, about 0.5 mAh an hour
# of use, against a 20 mA idle.
now_epoch() { if [ -n "${NOW}" ]; then echo "${NOW}"; else date +%s; fi; }

borrow_due() {
	[ -e "${WIFI_IDLED}" ] || return 1
	[ -e "${BORROWED}" ] || return 0
	last="$(cat "${BORROWED}" 2>/dev/null)"
	case "${last}" in '' | *[!0-9]*) return 0 ;; esac
	[ $(($(now_epoch) - last)) -ge "${BORROW_EVERY}" ]
}

borrowed=0
give_back() {
	[ "${borrowed}" -eq 1 ] || return 0
	borrowed=0
	"${WIFI}" idle-off >/dev/null 2>&1 &&
		say "the radio is idled off again" ||
		say "the radio stays up: something else is using Wi-Fi"
}

borrow_radio() {
	borrow_due || return 1
	now_epoch >"${BORROWED}" 2>/dev/null || true
	# The idle work lock, held shared on descriptor 8 until this process
	# exits, as every participant in transparent idle holds it.
	if [ -e "${IDLE_WORK}" ]; then
		exec 8<"${IDLE_WORK}"
		flock -s 8 2>/dev/null || true
	fi
	"${WIFI}" borrow >/dev/null 2>&1 || {
		say "the radio could not be borrowed"
		return 1
	}
	borrowed=1
	say "borrowed the idled radio for the hourly forecast"
	waited=0
	while ! has_default_route && [ "${waited}" -lt "${ROUTE_WAIT}" ]; do
		sleep 1
		waited=$((waited + 1))
	done
	return 0
}

do_fetch() {
	fixture="${1:-}"

	place=$(conf_value weather-place)
	lat=$(conf_value weather-lat)
	lon=$(conf_value weather-lon)

	# All three or none. Two of them is not half a location: the launcher
	# refuses the same combination and shows "Set your location", so
	# fetching on a guess would put a forecast under a cell that says there
	# is not one.
	if [ -z "${place}" ] || [ -z "${lat}" ] || [ -z "${lon}" ]; then
		say "no location set in ${HOME_CONF}, nothing to fetch"
		return 0
	fi

	tmp="${TMPDIR:-/tmp}/${PROG}.$$"
	# shellcheck disable=SC2064  # $tmp is wanted now, not at trap time
	trap "rm -f '${tmp}'; give_back" EXIT INT TERM

	if [ -n "${fixture}" ]; then
		[ -r "${fixture}" ] || die "no such fixture: ${fixture}"
		cp "${fixture}" "${tmp}" || die "cannot read ${fixture}"
		say "using ${fixture} instead of asking the network"
	else
		has_default_route || borrow_radio || true
		has_default_route ||
			{
				say "no default route, so nothing is being asked"
				return 0
			}
		# The parameter set, transcribed from joan-dashboard's
		# fetch_weather and its weather glance. current carries what
		# the cell shows and what the page's top block shows; daily
		# carries the rows. timezone=auto so the day boundaries are the
		# reader's own rather than UTC's, which is what makes "Today"
		# mean today.
		fetch_with_curl "${FORECAST_URL}" \
			--data-urlencode "latitude=${lat}" \
			--data-urlencode "longitude=${lon}" \
			--data-urlencode "current=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m" \
			--data-urlencode "daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,sunrise,sunset" \
			--data-urlencode "timezone=auto" \
			--data-urlencode "forecast_days=${FORECAST_DAYS}" \
			--output "${tmp}" ||
			die "the forecast could not be fetched"
	fi

	looks_like_json "${tmp}" ||
		die "what came back is not a response - leaving the last forecast alone"

	if install_body "${tmp}" weather.json weather.stamp; then
		say "new forecast for ${place}"
		signal_launcher
	else
		# Deliberately quiet on the panel and loud in the log. See the
		# note on SIGUSR1 at the top of this file.
		say "the forecast for ${place} has not changed"
	fi
}

do_geocode() {
	name="${1:-}"
	fixture="${2:-}"
	[ -n "${name}" ] || die "geocode needs a name to look for"

	tmp="${TMPDIR:-/tmp}/${PROG}.$$"
	# shellcheck disable=SC2064
	trap "rm -f '${tmp}'" EXIT INT TERM

	if [ -n "${fixture}" ]; then
		[ -r "${fixture}" ] || die "no such fixture: ${fixture}"
		cp "${fixture}" "${tmp}" || die "cannot read ${fixture}"
	else
		has_default_route || die "no default route, so no place can be looked up"
		# --data-urlencode with --get is what percent-encodes the name,
		# so a town with a space or an accent in it is asked about
		# correctly and this script needs no encoder of its own.
		fetch_with_curl "${GEOCODE_URL}" \
			--data-urlencode "name=${name}" \
			--data-urlencode "count=${GEOCODE_COUNT}" \
			--data-urlencode "language=en" \
			--data-urlencode "format=json" \
			--output "${tmp}" ||
			die "the place list could not be fetched"
	fi

	looks_like_json "${tmp}" || die "what came back is not a place list"

	# NO SIGNAL. The launcher started this one itself and is watching the
	# child rather than waiting to be told, and a signal here would cost a
	# full-panel repaint for a list that is drawn on the next frame anyway.
	install_body "${tmp}" geocode.json geocode.stamp || true
	say "place list for ${name} written"
}

usage() {
	cat <<'EOF'
usage: libra2-weather fetch [--fixture FILE]
       libra2-weather geocode NAME [--fixture FILE]
EOF
}

cmd="${1:-}"
# Not `[ $# -gt 0 ] && shift`: under set -e that whole AND-list fails when
# there are no arguments, and the script would exit before printing the usage
# it exists to print.
if [ $# -gt 0 ]; then
	shift
fi

case "${cmd}" in
fetch)
	fixture=""
	while [ $# -gt 0 ]; do
		case "$1" in
		--fixture)
			shift
			[ $# -gt 0 ] || die "--fixture needs a path"
			fixture="$1"
			;;
		*) die "unexpected argument: $1" ;;
		esac
		shift
	done
	do_fetch "${fixture}"
	;;
geocode)
	[ $# -gt 0 ] || die "geocode needs a name to look for"
	name="$1"
	shift
	fixture=""
	while [ $# -gt 0 ]; do
		case "$1" in
		--fixture)
			shift
			[ $# -gt 0 ] || die "--fixture needs a path"
			fixture="$1"
			;;
		*) die "unexpected argument: $1" ;;
		esac
		shift
	done
	do_geocode "${name}" "${fixture}"
	;;
-h | --help | help)
	usage
	;;
*)
	usage >&2
	exit 1
	;;
esac
