#!/bin/sh
# check-report -- E9 (s6-policy-common 1.2.6): makes the answer of a readiness
# check visible.
#
# Use in data/check:   exec /usr/lib/s6-policy-common/bin/check-report <command> [arg...]
#
# Measured on 23.09.2026 (container kat): a check started by s6-notifyoncheck
# inherits the descriptors of the run script -- stdout goes to the unit's
# logger pipeline, stderr to the catch-all (/run/uncaught-logs). That a failing
# check "does not say why" is therefore down to the checks themselves: curl -s,
# grep -q, 2>/dev/null stay silent, and whatever does go to stderr is not in the
# unit's log.
#
# check-report runs the command, collects stdout and stderr, and writes to
# stdout (i.e. the unit log):
#   * "check: not ready (rc N): <first line>"  -- only when the message differs
#     from the previous attempt; with -w 2000 -n 150 there would otherwise be
#     up to 150 identical lines per start,
#   * "check: ready"                          -- on the first success after a
#     failure (or on the very first attempt).
# (Until 1.2.7 the words were German: "bereit" / "nicht bereit".)
# The command's exit status is passed through unchanged; it alone decides
# readiness.
#
# State: /run/check-report/<unit>, the unit being the name of the service
# directory (the check runs with the service directory as working directory).
set -u
[ $# -ge 1 ] || { echo "check-report: usage: check-report prog [args...]" >&2; exit 100; }
unit=$(basename "$(pwd)")
sdir=/run/check-report
mkdir -p "$sdir" 2>/dev/null
last="$sdir/$unit"

out=$("$@" 2>&1); rc=$?
if [ "$rc" -eq 0 ]; then
  msg="ready"
else
  first=$(printf '%s\n' "$out" | sed -n '/./{p;q}')
  msg="not ready (rc $rc): ${first:-no output}"
fi
prev=$(cat "$last" 2>/dev/null || true)
if [ "$msg" != "$prev" ]; then
  echo "check: $msg"
  printf '%s\n' "$msg" > "$last" 2>/dev/null
fi
exit "$rc"
