#!/bin/sh
# Container only: prepares cgroup v2 for a nested container manager. All
# processes move into the leaf init.scope, so the namespaced root stays an
# empty domain whose controllers can be delegated; LXCFS then reports the
# whole container.
CG=/sys/fs/cgroup

[ "$(stat -fc %T "$CG" 2>/dev/null)" = cgroup2fs ] ||
	mount -t cgroup2 -o nsdelegate,memory_recursiveprot,nosuid,nodev,noexec cgroup2 "$CG" 2>/dev/null
[ -e "$CG/cgroup.controllers" ] || exit 0

mkdir -p "$CG/init.scope"
echo 1 >"$CG/init.scope/cgroup.procs" 2>/dev/null || :

# bounded; the builtin echo, as an external one would fork into the cgroup being emptied
i=0
while [ "$i" -lt 20 ]; do
	while read -r pid; do echo "$pid" >"$CG/init.scope/cgroup.procs" 2>/dev/null || :; done <"$CG/cgroup.procs"
	[ -n "$(cat "$CG/cgroup.procs" 2>/dev/null)" ] || break
	i=$((i + 1))
done

# per controller, some (cpu with realtime tasks) may refuse
read -r controllers <"$CG/cgroup.controllers"
for c in $controllers; do
	echo "+$c" >"$CG/cgroup.subtree_control" 2>/dev/null || :
done
exit 0
