#!/bin/sh
# power-moment MOMENT [--force] — run every module's code for one power moment (novox/hq ADR 0211).
# Shipped by the mesh's power module; edit the catalogue.
#
# MOMENT is after-boot, before-sleep, after-wake, before-shutdown, on-mains or on-battery, or
# `supply`, which reads the machine's power source and runs on-mains or on-battery once per change.
#
# The moment's file holds what the controller placed: each module's code under a line `# <module>`.
# Each module's piece runs on its own, with sh, as root, bounded by MESH_POWER_BOUND seconds
# (default 30) and killed 5 s after that, so one module that hangs cannot hold the machine awake or
# stop the next module. Every outcome goes to the journal under the tag mesh-power.
set -u

moment=${1:-}
force=${2:-}
moments=/etc/mesh-power/moments
bound=${MESH_POWER_BOUND:-30}
runtime=/run/mesh-power

say() { logger -t mesh-power -- "$*" 2>/dev/null || true; printf '%s\n' "$*"; }

# The power source as the kernel says it: on mains when any Mains supply is online. A machine with
# no Mains supply (a desktop, a server, a USB-C source only) has no source to change.
source_now() {
	found=no
	for s in /sys/class/power_supply/*; do
		[ "$(cat "$s/type" 2>/dev/null)" = Mains ] || continue
		found=yes
		[ "$(cat "$s/online" 2>/dev/null)" = 1 ] && { echo on-mains; return; }
	done
	[ "$found" = yes ] && echo on-battery || echo none
}

case "$moment" in
supply)
	now=$(source_now)
	[ "$now" = none ] && exit 0
	mkdir -p "$runtime"
	last=$(cat "$runtime/source" 2>/dev/null || true)
	[ "$now" = "$last" ] && [ "$force" != --force ] && exit 0
	echo "$now" >"$runtime/source"
	moment=$now
	;;
after-boot | before-sleep | after-wake | on-mains | on-battery) ;;
before-shutdown)
	# Run only while the machine is really going down. The unit that runs it is stopped at shutdown,
	# and also when the module is taken off the machine; the second must not run anyone's shutdown code.
	state=$(systemctl is-system-running 2>/dev/null || true)
	if [ "$state" != stopping ] && [ "$force" != --force ]; then
		say "moment=before-shutdown skipped: the system is $state, not stopping"
		exit 0
	fi
	;;
*)
	echo "power-moment: no moment $moment (after-boot, before-sleep, after-wake, before-shutdown, on-mains, on-battery, supply)" >&2
	exit 2
	;;
esac

file="$moments/$moment"
[ -r "$file" ] || { say "moment=$moment: nothing placed"; exit 0; }

work=$(mktemp -d) || exit 1
trap 'rm -rf "$work"' EXIT

# One file per module piece, in the order the controller placed them. A line that is exactly
# "# <module name>" opens a piece; lines before the first are the holder's own header.
awk -v dir="$work" '
	/^# [a-z0-9][a-z0-9-]*$/ { n++; name = substr($0, 3); out = sprintf("%s/%03d-%s", dir, n, name); next }
	n > 0 { print > out }
' "$file"

ran=0 failed=0
for piece in "$work"/*; do
	[ -e "$piece" ] || continue
	module=${piece##*/}
	module=${module#*-}
	start=$(date +%s)
	timeout --kill-after=5 "$bound" sh "$piece" </dev/null >"$piece.out" 2>&1
	rc=$?
	took=$(($(date +%s) - start))
	ran=$((ran + 1))
	case $rc in
	0) say "moment=$moment module=$module ok in ${took}s" ;;
	124 | 137) failed=$((failed + 1)); say "moment=$moment module=$module ended after ${bound}s: it did not finish" ;;
	*) failed=$((failed + 1)); say "moment=$moment module=$module exited $rc: $(tail -n 3 "$piece.out" | tr '\n' ' ')" ;;
	esac
done
say "moment=$moment: $ran piece(s), $failed failed"
exit 0
