#!/sbin/openrc-run

description="Mount cgroups inside LXC container."

mount_opts="nodev,noexec,nosuid"

depend() {
	keyword lxc
	need sysfs
}

cgroup_mode() {
	if grep -x "^[[:digit:]]:cpuset:/" /proc/1/cgroup > /dev/null ; then
		echo "hybrid"
	else
		echo "unified"
	fi
}

setup_hybrid() {
	ebegin "Mounting cgroups in a hybrid layout"

	local retval=0
	local name

	if ! mount -t tmpfs -o "$mount_opts" tmpfs /sys/fs/cgroup ; then
		echo "Unable to mount /sys/fs/cgroup"
		eend 1
		return 1
	fi

	cat /proc/1/cgroup | while read line ; do
		controller="$(echo $line | cut -d ':' -f 2)"

		case "$controller" in
			"")
				mkdir -p /sys/fs/cgroup/unified
				mount -n -t cgroup2 -o "$mount_opts" cgroup2 /sys/fs/cgroup/unified || retval=1
				;;
			"name="*)
				name="$(echo $controller | cut -d '=' -f 2)"
				mountinfo -q "/sys/fs/cgroup/$name" && continue

				mkdir -p "/sys/fs/cgroup/$name"
				mount -n -t cgroup -o "none,$mount_opts,name=$name" \
					cgroup "/sys/fs/cgroup/$name" || retval=1
				;;
			*)
				mountinfo -q "/sys/fs/cgroup/$controller" && continue

				mkdir -p "/sys/fs/cgroup/$controller"
				mount -n -t cgroup -o "$mount_opts,$controller" \
					cgroup "/sys/fs/cgroup/$controller" || retval=1
				;;
		esac
	done

	if ! mountinfo -q /sys/fs/cgroup/openrc ; then
		rm -rf /sys/fs/cgroup/openrc
		ln -sf /sys/fs/cgroup/systemd /sys/fs/cgroup/openrc
	fi

	mount -o remount,ro tmpfs /sys/fs/cgroup

	eend $retval
}

setup_unified() {
	ebegin "Mounting cgroups in a unified layout"

	local retval=0

	mkdir /sys/fs/cgroup/init.scope
	echo 1 > /sys/fs/cgroup/init.scope/cgroup.procs

	eend $retval
}

start() {
	[ -e /proc/cgroups ] || return 0

	local mode=$(cgroup_mode)

	case "$mode" in
		hybrid) setup_hybrid ;;
		unified) setup_unified ;;
		*) echo "Unknown cgroup mode '$mode'" ;;
	esac
}
