#!/usr/bin/env bash
# kernelwatch-agent: collect kernel/update state on a Debian or Ubuntu host and
# report it to the kernelwatch server. Run by kernelwatch-agent.timer.
#
# The agent only gathers facts; the server decides what they mean, so status
# rules can change without redeploying agents.
set -euo pipefail

AGENT_VERSION=0.11.0

# Prefix for every file the agent reads. Only the test suite sets this.
ROOT=${KERNELWATCH_ROOT:-}
CONF=${KERNELWATCH_CONF:-$ROOT/etc/kernelwatch/agent.conf}

usage() {
	cat <<EOF
Usage: kernelwatch-agent [--print] [--help]

Collects kernel and package update state and POSTs it to the kernelwatch server.

  --print   print the JSON report to stdout instead of sending it
  --help    show this help

Configuration is read from $CONF.
EOF
}

die() {
	echo "kernelwatch-agent: $*" >&2
	exit 1
}

# --- JSON helpers -----------------------------------------------------------

json_str() {
	local s
	s=$(printf '%s' "$1" | tr -d '\000-\037')
	s=${s//\\/\\\\}
	s=${s//\"/\\\"}
	printf '"%s"' "$s"
}

# Integer or null.
json_int() {
	if [[ $1 =~ ^-?[0-9]+$ ]]; then printf '%s' "$1"; else printf 'null'; fi
}

json_bool() {
	if [[ $1 == 1 ]]; then printf 'true'; else printf 'false'; fi
}

# JSON array of strings from newline-separated input on stdin.
json_str_array() {
	local line first=1
	printf '['
	while IFS= read -r line; do
		[[ -z $line ]] && continue
		((first)) || printf ','
		first=0
		json_str "$line"
	done
	printf ']'
}

# --- config -----------------------------------------------------------------

SERVER_URL=
TOKEN_FILE=$ROOT/etc/kernelwatch/agent.token
CA_FILE=
TIMEOUT=30
# Name to report instead of `hostname -f`, for a host registered under another name.
REPORT_HOSTNAME=

load_config() {
	[[ -r $CONF ]] || return 0
	local key value
	while IFS='=' read -r key value; do
		key=${key//[[:space:]]/}
		[[ -z $key || $key == \#* ]] && continue
		value=${value#"${value%%[![:space:]]*}"}
		value=${value%"${value##*[![:space:]]}"}
		value=${value#\"}
		value=${value%\"}
		case $key in
		SERVER_URL) SERVER_URL=$value ;;
		TOKEN_FILE) TOKEN_FILE=$value ;;
		CA_FILE) CA_FILE=$value ;;
		TIMEOUT) TIMEOUT=$value ;;
		REPORT_HOSTNAME) REPORT_HOSTNAME=$value ;;
		*) echo "kernelwatch-agent: ignoring unknown config key '$key'" >&2 ;;
		esac
	done <"$CONF"
}

# --- collectors -------------------------------------------------------------

os_release_field() {
	local key=$1 k v
	[[ -r $ROOT/etc/os-release ]] || return 0
	while IFS='=' read -r k v; do
		if [[ $k == "$key" ]]; then
			v=${v#\"}
			v=${v%\"}
			printf '%s' "$v"
			return 0
		fi
	done <"$ROOT/etc/os-release"
}

# Installed kernel image versions (e.g. 6.12.57+deb13-amd64), oldest first.
installed_kernels() {
	dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' \
		'linux-image-[0-9]*' 'linux-image-unsigned-[0-9]*' 2>/dev/null |
		awk '$1 == "ii" { print $2 }' |
		grep -v -- '-dbg$' |
		sed -E 's/^linux-image-(unsigned-)?//' |
		sort -uV || true
}

# Package version of the image for the running kernel (e.g. 6.12.57-1). The
# server compares it with the build in `uname -v` to spot in-place upgrades.
running_kernel_pkg_version() {
	dpkg-query -W -f='${db:Status-Abbrev} ${Version}\n' \
		"linux-image-$1" "linux-image-unsigned-$1" 2>/dev/null |
		awk '$1 == "ii" { print $2; exit }' || true
}

# Results of `needrestart -b`, written as root by kernelwatch-needrestart.service
# (which this agent's unit pulls in, so it runs just before each report). The
# agent never runs needrestart itself: unprivileged it can't read Ubuntu's
# root-only /boot images or other users' processes, and gives wrong answers.
NEEDRESTART_FILE=$ROOT/run/kernelwatch/needrestart
NEEDRESTART_MAX_AGE=7200

# Sets NR_* from the results file, if it's there and fresh. KSTA: 0 unknown,
# 1 current, 2 ABI-compatible upgrade pending, 3 version upgrade pending.
# UCSTA (CPU microcode, bare metal only; needrestart skips it in VMs): 0 unknown,
# 1 current, 2 a newer revision is installed but needs a reboot to load. UCCUR
# and UCEXP are the loaded and installed revisions.
NR_OK=0
NR_KSTA=
NR_KEXP=
NR_UCSTA=
NR_UCCUR=
NR_UCEXP=
NR_SVCS=
NR_SESS=0
read_needrestart() {
	local mtime line
	mtime=$(stat -c %Y "$NEEDRESTART_FILE" 2>/dev/null) || return 0
	(($(date +%s) - mtime <= NEEDRESTART_MAX_AGE)) || return 0
	NR_OK=1
	while IFS= read -r line; do
		case $line in
		NEEDRESTART-KSTA:*) NR_KSTA=${line#*: } ;;
		NEEDRESTART-KEXP:*) NR_KEXP=${line#*: } ;;
		NEEDRESTART-UCSTA:*) NR_UCSTA=${line#*: } ;;
		NEEDRESTART-UCCUR:*) NR_UCCUR=${line#*: } ;;
		NEEDRESTART-UCEXP:*) NR_UCEXP=${line#*: } ;;
		NEEDRESTART-SVC:*) NR_SVCS+=${line#*: }$'\n' ;;
		NEEDRESTART-SESS:*) NR_SESS=$((NR_SESS + 1)) ;;
		esac
	done <"$NEEDRESTART_FILE"
}

# Ubuntu Livepatch status, flattened by kernelwatch-livepatch.service (root; the
# Livepatch snap won't run unprivileged). Absent when Livepatch isn't enabled.
LIVEPATCH_FILE=$ROOT/run/kernelwatch/livepatch
LIVEPATCH_MAX_AGE=7200

# Sets LP_* from the file, if it's there and fresh.
LP_STATE=
LP_CHECK=
LP_SUPPORTED=
LP_UPGRADE=
LP_FIXES=
read_livepatch() {
	local mtime line
	mtime=$(stat -c %Y "$LIVEPATCH_FILE" 2>/dev/null) || return 0
	(($(date +%s) - mtime <= LIVEPATCH_MAX_AGE)) || return 0
	while IFS= read -r line; do
		case $line in
		LIVEPATCH-STATE:*) LP_STATE=${line#*: } ;;
		LIVEPATCH-CHECK:*) LP_CHECK=${line#*: } ;;
		LIVEPATCH-SUPPORTED:*) LP_SUPPORTED=${line#*: } ;;
		LIVEPATCH-UPGRADE-REQUIRED:*) LP_UPGRADE=${line#*: } ;;
		LIVEPATCH-FIXES:*) LP_FIXES=${line#*: } ;;
		esac
	done <"$LIVEPATCH_FILE"
}

# How kernelwatch's helper units last ended, as recorded by kernelwatch-unit-result
# (their ExecStopPost=): one "NAME RESULT EXIT_CODE EXIT_STATUS FAILURES" line per
# unit that ran recently, e.g. "apt-update exit-code exited 100 3", FAILURES being
# failed runs in a row. This unit only Wants= them, so when they fail the report
# still goes out, with stale or missing data, and nothing else would say why.
# Livepatch isn't listed: its unit fails by design where the snap is installed
# but Livepatch isn't enabled, and its health is reported on its own.
HELPER_UNITS=(apt-update needrestart)
HELPER_MAX_AGE=7200
helper_units() {
	local name file mtime now result='' code='' status='' failures=''
	now=$(date +%s)
	for name in "${HELPER_UNITS[@]}"; do
		file=$ROOT/run/kernelwatch/$name.result
		mtime=$(stat -c %Y "$file" 2>/dev/null) || continue
		((now - mtime <= HELPER_MAX_AGE)) || continue
		read -r result code status failures _ <"$file" || [[ -n $result ]] || continue
		[[ $result =~ ^[a-z-]{1,32}$ && $code =~ ^[a-z-]{1,16}$ &&
			$status =~ ^[A-Za-z0-9-]{1,16}$ && $failures =~ ^[0-9]{1,6}$ ]] || continue
		printf '%s %s %s %s %s\n' "$name" "$result" "$code" "$status" "$failures"
	done
}

# String, or null when empty.
json_str_or_null() {
	if [[ -n $1 ]]; then json_str "$1"; else printf 'null'; fi
}

# Simulated dist-upgrade. Reads only: no locks, no cache files written.
# dist-upgrade (not upgrade) so new-ABI kernel packages pulled in by the
# meta-package show up. C locale because we parse apt's messages.
#
# apt skips phasing in chroots, detected with `ischroot -t`, which compares /
# with /proc/1/root. Unprivileged we can't read /proc/1/root, so ischroot
# answers "chroot" and apt would offer every phased update. We're not in one:
# say so, and apt applies phasing from /etc/machine-id like it does for root.
#
# apt's stderr goes to the file named by $1. A failed simulation prints nothing,
# which would otherwise read as "no updates", so the caller reports the failure.
apt_simulation() {
	LC_ALL=C apt-get -s -q \
		-o Dir::Bin::ischroot=/bin/false \
		-o Debug::NoLocking=true \
		-o Dir::Cache::pkgcache= \
		-o Dir::Cache::srcpkgcache= \
		dist-upgrade 2>"$1"
}

# Why apt failed, from its stderr on stdin: the first "E:" line, else the first
# line, else the exit status in $1.
apt_error() {
	local line first=
	while IFS= read -r line; do
		if [[ $line == 'E: '* ]]; then
			printf '%s' "${line#E: }"
			return 0
		fi
		[[ -z $first && -n $line ]] && first=$line
	done
	printf '%s' "${first:-apt-get exited with status $1}"
}

# Packages Ubuntu is holding back from this host for now (phased updates). apt
# lists them in an indented block instead of as Inst lines, so they're not in
# the upgradable counts. Debian doesn't phase updates.
phased_packages() {
	sed -n '/deferred due to phasing:$/,/^[^ ]/{/^ /p}' |
		tr -s ' ' '\n' | sed '/^$/d' | sort -u
}

# Seconds since apt last refreshed its package lists, or empty if unknown.
# Both stamps are touched only after a successful update: update-success-stamp by
# Ubuntu's update-notifier hook and kernelwatch-apt-update.service, update-stamp by
# apt-daily. lists/partial changes on every attempt, failed ones too, so it's only
# a last resort for hosts that have neither (Debian without either timer).
apt_lists_age() {
	local newest=0 f m
	for f in \
		"$ROOT/var/lib/apt/periodic/update-success-stamp" \
		"$ROOT/var/lib/apt/periodic/update-stamp"; do
		m=$(stat -c %Y "$f" 2>/dev/null) || continue
		((m > newest)) && newest=$m
	done
	if ((newest == 0)); then
		newest=$(stat -c %Y "$ROOT/var/lib/apt/lists/partial" 2>/dev/null) || return 0
	fi
	printf '%s' $(($(date +%s) - newest))
}

# The release's security suite (trixie-security, noble-security) and how old,
# in seconds, apt's newest list for it is, as "SUITE AGE". The age is by the
# list's Date: field, when the repository last published as of apt's last
# successful fetch, so it grows if fetches fail even while other repositories
# refresh. AGE is empty if apt has no list for the suite: it isn't in the
# sources, and security updates can't arrive. Nothing at all without a release
# codename. Lists are matched by their Suite: (Ubuntu) or Codename: (Debian)
# field, since file names depend on the mirror; with several mirrors the newest
# counts.
APT_LISTS_DIR=$ROOT/var/lib/apt/lists
security_repo() {
	local codename suite f published t newest=0 now
	codename=$(os_release_field VERSION_CODENAME)
	[[ -n $codename ]] || codename=$(os_release_field UBUNTU_CODENAME)
	[[ $codename =~ ^[a-z]+$ ]] || return 0
	suite=$codename-security
	for f in "$APT_LISTS_DIR"/*_InRelease "$APT_LISTS_DIR"/*_Release; do
		[[ -f $f ]] || continue
		# The fields come before the checksum lists, which can be long.
		published=$(awk -v want="$suite" '
			/^(MD5Sum|SHA1|SHA256|SHA512):/ { exit }
			($1 == "Suite:" || $1 == "Codename:") && $2 == want { found = 1 }
			$1 == "Date:" { sub(/^Date:[ \t]*/, ""); date = $0 }
			END { if (found) print (date == "" ? "-" : date) }' "$f" 2>/dev/null) || continue
		[[ -n $published ]] || continue
		if [[ $published == - ]] || ! t=$(date -d "$published" +%s 2>/dev/null); then
			# apt sets a list's mtime from the server's Last-Modified.
			t=$(stat -c %Y "$f" 2>/dev/null) || continue
		fi
		((t > newest)) && newest=$t
	done
	printf '%s ' "$suite"
	if ((newest > 0)); then
		now=$(date +%s)
		printf '%s' $((now > newest ? now - newest : 0))
	fi
	return 0
}

# Installed packages on hold (`apt-mark hold`, or dpkg's "hold" selection). apt
# never upgrades them and the simulation doesn't list them, so their updates,
# security ones included, don't show up anywhere else.
held_packages() {
	dpkg-query -W -f='${db:Status-Abbrev}\t${binary:Package}\n' 2>/dev/null |
		awk -F '\t' 'substr($1, 1, 2) == "hi" { print $2 }' |
		sort -u || true
}

# Size and free space of the filesystem holding /boot, in KiB, as "SIZE FREE";
# empty if df can't tell. That's the root filesystem when /boot isn't its own
# mount. A full /boot makes the next kernel's postinst fail, so the host stays
# on its old kernel with apt half-done.
boot_space() {
	df -Pk "$ROOT/boot" 2>/dev/null |
		awk 'NR == 2 && $2 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ { print $2, $4 }' || true
}

# Free space in KiB and mount point of the filesystem holding $1, as "FREE MOUNT";
# empty if df can't tell. The mount point is everything after df's fifth column,
# so one with spaces survives.
fs_free() {
	df -Pk "$1" 2>/dev/null |
		awk 'NR == 2 && $4 ~ /^[0-9]+$/ {
			m = $0
			for (i = 1; i <= 5; i++) sub(/^[^ ]+ +/, "", m)
			print $4, m
		}' || true
}

# Archives apt downloads into before installing. The agent assumes the default.
APT_ARCHIVES=$ROOT/var/cache/apt/archives

# Space the pending upgrades need, in KiB, as "DOWNLOAD INSTALL", from the
# simulation's Inst lines on stdin; empty if apt-cache can't say. A simulation
# doesn't print apt's "Need to get" and "additional disk space" lines, so this
# adds them up from the package records instead: Size for each .deb not already
# in $APT_ARCHIVES (unattended-upgrades often downloads ahead), and the growth in
# Installed-Size, the new versions' minus the installed ones'. INSTALL can be
# negative. Packages the upgrade removes aren't counted, so it errs high.
upgrade_space() {
	local name f3 f4 ver file size isize records dl=0 grow=0
	local -a specs=() upgraded=()
	while read -r _ name f3 f4 _; do
		[[ -n $name ]] || continue
		# "Inst NAME [OLD] (NEW ...)" for an upgrade, "Inst NAME (NEW ...)" for a new package.
		if [[ $f3 == '['* ]]; then
			ver=${f4#(}
			upgraded+=("$name")
		else
			ver=${f3#(}
		fi
		specs+=("$name=$ver")
	done
	if ((${#specs[@]} == 0)); then
		echo "0 0"
		return 0
	fi

	# apt stores archives as NAME_VERSION_ARCH.deb with ':' (epochs) as %3a.
	records=$(LC_ALL=C apt-cache -q \
		-o Dir::Cache::pkgcache= \
		-o Dir::Cache::srcpkgcache= \
		show "${specs[@]}" 2>/dev/null | awk 'BEGIN { RS = "" } {
			pkg = ver = arch = ""; size = isize = 0
			n = split($0, line, "\n")
			for (i = 1; i <= n; i++) {
				if (line[i] ~ /^Package: /) pkg = substr(line[i], 10)
				else if (line[i] ~ /^Version: /) ver = substr(line[i], 10)
				else if (line[i] ~ /^Architecture: /) arch = substr(line[i], 15)
				else if (line[i] ~ /^Size: /) size = substr(line[i], 7) + 0
				else if (line[i] ~ /^Installed-Size: /) isize = substr(line[i], 17) + 0
			}
			if (pkg == "" || ver == "") next
			gsub(/:/, "%3a", ver)
			file = pkg "_" ver "_" arch ".deb"
			if (seen[file]++) next
			print file, size, isize
		}') || return 0
	[[ -n $records ]] || return 0

	while read -r file size isize; do
		grow=$((grow + isize))
		[[ -e $APT_ARCHIVES/$file ]] || dl=$((dl + size))
	done <<<"$records"
	if ((${#upgraded[@]})); then
		while read -r isize; do
			[[ $isize =~ ^[0-9]+$ ]] && grow=$((grow - isize))
		done < <(dpkg-query -W -f='${Installed-Size}\n' "${upgraded[@]}" 2>/dev/null || true)
	fi
	echo "$(((dl + 1023) / 1024)) $grow"
}

# Packages dpkg didn't finish installing or removing: half-installed, unpacked,
# half-configured, awaiting or pending triggers, or flagged reinst-required.
# The same states `dpkg --audit` reports; usually a failed postinst, cleared by
# `dpkg --configure -a`. Reads the status database only.
unfinished_packages() {
	dpkg-query -W -f='${db:Status-Abbrev}\t${binary:Package}\n' 2>/dev/null |
		awk -F '\t' 'substr($1, 2, 1) ~ /[HUFWt]/ || substr($1, 3, 1) == "R" { print $2 }' |
		sort -u || true
}

# unattended-upgrades: "enabled", "disabled" or "not-installed". Enabled means the
# package is installed (not just its leftover config, dpkg state rc) and
# APT::Periodic::Unattended-Upgrade is set and not 0, which is what makes
# apt-daily-upgrade.service (apt.systemd.daily) run it.
unattended_upgrades_state() {
	local abbrev value
	abbrev=$(dpkg-query -W -f='${db:Status-Abbrev}' unattended-upgrades 2>/dev/null || true)
	if [[ $abbrev != ii* ]]; then
		printf 'not-installed'
		return 0
	fi
	value=$(apt-config dump APT::Periodic::Unattended-Upgrade 2>/dev/null |
		sed -n 's/^APT::Periodic::Unattended-Upgrade "\(.*\)";$/\1/p' | tail -n1 || true)
	if [[ -n $value && $value != 0 ]]; then printf 'enabled'; else printf 'disabled'; fi
}

# Seconds since the file at $1 was modified, or empty if it doesn't exist.
file_age() {
	local m
	m=$(stat -c %Y "$1" 2>/dev/null) || return 0
	printf '%s' $(($(date +%s) - m))
}

# apt.systemd.daily touches upgrade-stamp only when unattended-upgrade exits 0.
# unattended-upgrade writes its own stamp whenever a run gets far enough to know
# what it would do, even if it then fails (e.g. on a conffile prompt). So a newer
# run stamp than success stamp means it's running but failing.
UU_SUCCESS_STAMP=$ROOT/var/lib/apt/periodic/upgrade-stamp
UU_RUN_STAMP=$ROOT/var/lib/apt/periodic/unattended-upgrades-stamp
# Packages from its allowed origins it didn't upgrade (held, blacklisted, conffile
# prompt), space-separated; removed when there are none.
UU_KEPT_FILE=$ROOT/var/lib/unattended-upgrades/kept-back

# Ubuntu Pro state from the pro client's status cache, which it keeps
# world-readable (the token lives in private/ next to it). Prints "ATTACHED ESM"
# (e.g. "true enabled", "false -"); nothing if there's no file or it can't be
# read, as on Debian. Past standard support, only esm-infra keeps main patched.
PRO_STATUS_FILE=$ROOT/var/lib/ubuntu-advantage/status.json
ubuntu_pro() {
	[[ -r $PRO_STATUS_FILE ]] || return 0
	command -v python3 >/dev/null || return 0
	python3 -I -c '
import json, re, sys
d = json.load(open(sys.argv[1]))
attached = d.get("attached") is True
esm = next((s.get("status") for s in d.get("services") or []
            if isinstance(s, dict) and s.get("name") == "esm-infra"), None)
esm = esm if attached and isinstance(esm, str) and re.fullmatch(r"[a-z/-]{1,20}", esm) else "-"
print("true" if attached else "false", esm)
' "$PRO_STATUS_FILE" 2>/dev/null || true
}

uptime_seconds() {
	local up _
	[[ -r $ROOT/proc/uptime ]] || return 0
	read -r up _ <"$ROOT/proc/uptime"
	printf '%s' "${up%%.*}"
}

build_report() {
	local running newest kernels sim inst sim_err rc apt_ok=1 apt_err='' reboot_file=0 reboot_pkgs=
	local boot_size='' boot_free='' pro_attached='' pro_esm='' sec_suite='' sec_age=''
	local up_dl='' up_grow='' arch_free='' arch_mount='' usr_free='' usr_mount=''

	running=$(uname -r)
	kernels=$(installed_kernels)
	newest=$(tail -n1 <<<"$kernels")
	read_needrestart
	read_livepatch

	sim_err=$(mktemp)
	if sim=$(apt_simulation "$sim_err"); then
		:
	else
		rc=$?
		apt_ok=0 sim=
		apt_err=$(apt_error "$rc" <"$sim_err")
	fi
	rm -f "$sim_err"
	inst=$(grep '^Inst ' <<<"$sim" || true)

	if [[ -e $ROOT/run/reboot-required ]]; then
		reboot_file=1
		[[ -r $ROOT/run/reboot-required.pkgs ]] && reboot_pkgs=$(sort -u "$ROOT/run/reboot-required.pkgs")
	fi

	read -r boot_size boot_free <<<"$(boot_space)" || true
	((apt_ok)) && { read -r up_dl up_grow <<<"$(upgrade_space <<<"$inst")" || true; }
	read -r arch_free arch_mount <<<"$(fs_free "$APT_ARCHIVES")" || true
	read -r usr_free usr_mount <<<"$(fs_free "$ROOT/usr")" || true
	read -r pro_attached pro_esm <<<"$(ubuntu_pro)" || true
	read -r sec_suite sec_age <<<"$(security_repo)" || true
	[[ $pro_esm == - ]] && pro_esm=

	printf '{'
	printf '"agent_version":%s,' "$(json_str "$AGENT_VERSION")"
	printf '"reported_hostname":%s,' "$(json_str "${REPORT_HOSTNAME:-$(hostname -f 2>/dev/null || hostname)}")"
	printf '"os_id":%s,' "$(json_str "$(os_release_field ID)")"
	printf '"os_version_id":%s,' "$(json_str "$(os_release_field VERSION_ID)")"
	printf '"os_pretty_name":%s,' "$(json_str "$(os_release_field PRETTY_NAME)")"
	printf '"kernel_running":%s,' "$(json_str "$running")"
	printf '"kernel_build":%s,' "$(json_str "$(uname -v)")"
	printf '"kernel_running_pkg_version":%s,' "$(json_str "$(running_kernel_pkg_version "$running")")"
	printf '"kernels_installed":%s,' "$(json_str_array <<<"$kernels")"
	printf '"kernel_newest_installed":%s,' "$(json_str "$newest")"
	printf '"needrestart_ksta":%s,' "$(json_int "$NR_KSTA")"
	printf '"needrestart_kexp":%s,' "$(json_str "$NR_KEXP")"
	printf '"needrestart_ucsta":%s,' "$(json_int "$NR_UCSTA")"
	printf '"needrestart_uccur":%s,' "$(json_str_or_null "$NR_UCCUR")"
	printf '"needrestart_ucexp":%s,' "$(json_str_or_null "$NR_UCEXP")"
	if ((NR_OK)); then
		printf '"services_need_restart":%s,' "$(sort -u <<<"$NR_SVCS" | json_str_array)"
		printf '"sessions_need_restart":%s,' "$NR_SESS"
	else
		printf '"services_need_restart":null,"sessions_need_restart":null,'
	fi
	printf '"reboot_required":%s,' "$(json_bool "$reboot_file")"
	printf '"reboot_required_pkgs":%s,' "$(json_str_array <<<"$reboot_pkgs")"
	if ((apt_ok)); then
		printf '"upgradable_count":%s,' "$(json_int "$(grep -c . <<<"$inst" || true)")"
		printf '"security_count":%s,' "$(json_int "$(grep -ci 'security' <<<"$inst" || true)")"
		printf '"phased_packages":%s,' "$(phased_packages <<<"$sim" | json_str_array)"
		printf '"kernel_upgradable":%s,' "$(awk '$2 ~ /^linux-image-/ { print $2 }' <<<"$inst" | json_str_array)"
	else
		printf '"upgradable_count":null,"security_count":null,"phased_packages":null,"kernel_upgradable":null,'
	fi
	printf '"apt_simulation_ok":%s,' "$(json_bool "$apt_ok")"
	printf '"apt_simulation_error":%s,' "$(json_str_or_null "$apt_err")"
	printf '"livepatch_state":%s,' "$(json_str_or_null "$LP_STATE")"
	printf '"livepatch_check_state":%s,' "$(json_str_or_null "$LP_CHECK")"
	printf '"livepatch_supported":%s,' "$(json_str_or_null "$LP_SUPPORTED")"
	printf '"livepatch_upgrade_required":%s,' "$(json_str_or_null "$LP_UPGRADE")"
	printf '"livepatch_fix_count":%s,' "$(json_int "$LP_FIXES")"
	printf '"boot_size_kb":%s,' "$(json_int "$boot_size")"
	printf '"boot_free_kb":%s,' "$(json_int "$boot_free")"
	printf '"upgrade_download_kb":%s,' "$(json_int "$up_dl")"
	printf '"upgrade_install_kb":%s,' "$(json_int "$up_grow")"
	printf '"apt_archives_free_kb":%s,' "$(json_int "$arch_free")"
	printf '"apt_archives_mount":%s,' "$(json_str_or_null "$arch_mount")"
	printf '"usr_free_kb":%s,' "$(json_int "$usr_free")"
	printf '"usr_mount":%s,' "$(json_str_or_null "$usr_mount")"
	printf '"dpkg_unfinished_packages":%s,' "$(unfinished_packages | json_str_array)"
	printf '"held_packages":%s,' "$(held_packages | json_str_array)"
	case $pro_attached in
	true | false) printf '"ubuntu_pro_attached":%s,' "$pro_attached" ;;
	*) printf '"ubuntu_pro_attached":null,' ;;
	esac
	printf '"ubuntu_esm_infra":%s,' "$(json_str_or_null "$pro_esm")"
	printf '"unattended_upgrades":%s,' "$(json_str "$(unattended_upgrades_state)")"
	printf '"unattended_upgrades_success_age_seconds":%s,' "$(json_int "$(file_age "$UU_SUCCESS_STAMP")")"
	printf '"unattended_upgrades_run_age_seconds":%s,' "$(json_int "$(file_age "$UU_RUN_STAMP")")"
	printf '"unattended_upgrades_kept_back":%s,' \
		"$( { [[ -r $UU_KEPT_FILE ]] && tr -s ' \t' '\n' <"$UU_KEPT_FILE"; } | sort -u | json_str_array)"
	printf '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
	printf '"security_repo_suite":%s,' "$(json_str_or_null "$sec_suite")"
	printf '"security_repo_age_seconds":%s,' "$(json_int "$sec_age")"
	printf '"helper_units":%s,' "$(helper_units | json_str_array)"
	printf '"uptime_seconds":%s' "$(json_int "$(uptime_seconds)")"
	printf '}\n'
}

send_report() {
	local payload=$1 token
	[[ -n $SERVER_URL ]] || die "SERVER_URL is not set in $CONF"

	# Prefer the systemd credential (LoadCredential=token:...).
	if [[ -n ${CREDENTIALS_DIRECTORY:-} && -r $CREDENTIALS_DIRECTORY/token ]]; then
		token=$(<"$CREDENTIALS_DIRECTORY/token")
	elif [[ -r $TOKEN_FILE ]]; then
		token=$(<"$TOKEN_FILE")
	else
		die "no token: neither \$CREDENTIALS_DIRECTORY/token nor $TOKEN_FILE is readable"
	fi
	token=${token//[[:space:]]/}
	[[ -n $token ]] || die "token is empty"

	local -a args=(--silent --show-error --fail-with-body
		--max-time "$TIMEOUT" --retry 3 --retry-delay 10 --retry-connrefused
		--header 'Content-Type: application/json'
		--data-binary "$payload"
		--config -)
	[[ -n $CA_FILE ]] && args+=(--cacert "$CA_FILE")

	# Token goes in via a curl config on stdin so it never appears in argv.
	printf 'header = "Authorization: Bearer %s"\n' "$token" |
		curl "${args[@]}" "${SERVER_URL%/}/api/v1/report" >/dev/null
}

main() {
	local mode=send
	case ${1:-} in
	--print) mode=print ;;
	--help | -h)
		usage
		return 0
		;;
	"") ;;
	*)
		usage >&2
		return 2
		;;
	esac

	load_config
	local report
	report=$(build_report)

	if [[ $mode == print ]]; then
		printf '%s\n' "$report"
	else
		send_report "$report"
		echo "kernelwatch-agent: report sent to $SERVER_URL"
	fi
}

main "$@"
