#!/bin/sh
# Records how a kernelwatch helper unit's run ended, for the agent to report.
# Run as the unit's ExecStopPost=, which systemd runs after every run, failed or
# not, with SERVICE_RESULT, EXIT_CODE and EXIT_STATUS set (systemd.exec(5)).
#
# Usage: kernelwatch-unit-result NAME
# Writes /run/kernelwatch/NAME.result as "RESULT EXIT_CODE EXIT_STATUS FAILURES",
# e.g. "exit-code exited 100 3", where FAILURES counts failed runs in a row and
# is 0 after a success. A missing value is written as "-".
set -u

name=${1:-}
case $name in
'' | *[!a-z0-9-]*)
	echo "usage: kernelwatch-unit-result NAME" >&2
	exit 2
	;;
esac
file=${KERNELWATCH_RUN_DIR:-/run/kernelwatch}/$name.result

result=${SERVICE_RESULT:--}
failures=0
if [ "$result" != success ]; then
	failures=$(awk '$4 ~ /^[0-9]+$/ { print $4 }' "$file" 2>/dev/null)
	failures=$((${failures:-0} + 1))
fi

printf '%s %s %s %s\n' "$result" "${EXIT_CODE:--}" "${EXIT_STATUS:--}" "$failures" >"$file.new" &&
	mv "$file.new" "$file"
