#!/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.4.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

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 ;;
		*) 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.
NR_OK=0
NR_KSTA=
NR_KEXP=
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-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"
}

# 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_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>/dev/null || true
}

# 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.
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" \
		"$ROOT/var/lib/apt/lists/partial"; do
		[[ -e $f ]] || continue
		m=$(stat -c %Y "$f" 2>/dev/null) || continue
		((m > newest)) && newest=$m
	done
	((newest > 0)) && printf '%s' $(($(date +%s) - newest))
	return 0
}

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 reboot_file=0 reboot_pkgs=

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

	sim=$(apt_simulation)
	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

	printf '{'
	printf '"agent_version":%s,' "$(json_str "$AGENT_VERSION")"
	printf '"reported_hostname":%s,' "$(json_str "$(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")"
	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")"
	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)"
	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 '"apt_lists_age_seconds":%s,' "$(json_int "$(apt_lists_age)")"
	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 "$@"
