#!/bin/sh
set -eu

# FIXME: what do we want to do on other init systems? are they even calling this script?
[ -d /run/systemd/system ] || exit 0

# Tell runsvdir(8) to shutdown:
kill -HUP "${MAINPID:-}" 2>/dev/null || true

# Systemd starts the ExecStop script (us) in the service's cgroup:
cgroup=`sed -E 's/^0:://;t;d' /proc/$$/cgroup`
[ -n "$cgroup" ] || exit 2
cgroup="/sys/fs/cgroup/$cgroup"
[ -d "$cgroup" ] || exit 3


# Now we leave the cgroup and wait for everything else in it do die.
#
# While it might seem appropriate to use "systemd-run --scope" to get our own
# cgroup, that doesn't actually work: systemd will notice that we're trying to
# start a unit during shutdown, log
#   Transaction for run-….scope/start is destructive (shutdown.target has 'start' job queued, but 'stop' is included in transaction).
# and refuse to execute our code.
# Hence, just put us into the root cgroup by hand:
echo $$ >/sys/fs/cgroup/cgroup.procs

while grep -qFx "populated 1" "$cgroup"/cgroup.events ; do
    sleep 0.1
done
