#!/bin/sh
# once UNIT PROG [ARGS...]  runs a stage of cloud-init, once per boot
# once --stopped UNIT       at the stop of UNIT: notes the live database of s6-rc
#
# s6-rc-update stops a unit under the old database and starts it under the
# new one: an up after such a stop is a restart by a structural change and
# ends with success without running PROG. A stop and start under the same
# database (svctl restart) runs PROG again.
set -u
D=/run/cloud-init-policy-s6
live() { readlink /run/s6-rc/compiled 2>/dev/null; }

if [ "${1:-}" = --stopped ]; then
	[ $# -eq 2 ] || { echo "usage: once --stopped UNIT" >&2; exit 100; }
	mkdir -p "$D" && live >"$D/$2.stopped"
	exit 0
fi
[ $# -ge 2 ] || { echo "usage: once UNIT PROG [ARGS...]" >&2; exit 100; }
unit=$1
shift
if [ -f "$D/$unit.stopped" ]; then
	was=$(cat "$D/$unit.stopped")
	rm -f "$D/$unit.stopped"
	if [ "$was" != "$(live)" ]; then
		echo "$unit: started again after a change of the s6-rc database; the stage ran in this boot already"
		exit 0
	fi
fi
exec "$@"
