#!/bin/sh

### BEGIN INIT INFO
# Provides:           cgroups-mount
# Required-Start:     $local_fs
# Required-Stop:      $local_fs
# Default-Start:      S
# Default-Stop:
# Short-Description:  Set up cgroup mounts.
# Description:
#  Control groups are a kernel mechanism for tracking and imposing
#  limits on resource usage on groups of tasks.
### END INIT INFO

. /lib/lsb/init-functions

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

cgroup_setup_hybrid() {
	log_begin_msg "Mounting cgroups in a hybrid layout"

	local retval=0
	local name
	local mount_opts="nodev,noexec,nosuid"

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

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

		case "$controller" in
			"")
				mkdir /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)"
				mkdir "/sys/fs/cgroup/$name"
				mount -n -t cgroup -o "none,$mount_opts,name=$name" \
					cgroup "/sys/fs/cgroup/$name" || retval=1
				;;
			*)
				mkdir "/sys/fs/cgroup/$controller"
				mount -n -t cgroup -o "$mount_opts,$controller" \
					cgroup "/sys/fs/cgroup/$controller" || retval=1
				;;
		esac
	done

	ln -sfn systemd /sys/fs/cgroup/elogind

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

	log_end_msg $retval
}

cgroup_setup_unified() {
	log_begin_msg "Mounting cgroups in a unified layout"

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

	log_end_msg 0
}

cgroup_setup() {
	local mode=$(cgroup_mode)

	case "$mode" in
		hybrid) cgroup_setup_hybrid ;;
		unified) cgroup_setup_unified ;;
		*)
			log_action_msg "Unknown cgroup mode '$mode'"
			return 1
			;;
	esac
}

case "$1" in
        start)
		cgroup_setup
                ;;

        status)
                if mountpoint -q /sys/fs/cgroup; then
                        log_success_msg 'cgroups hierarchy is mounted'
                        exit 0
                else
                        log_failure_msg 'cgroups hierarchy is not mounted'
                        exit 1
                fi
                ;;

        *)
                echo "Usage: $0 {start|status}"
                exit 1
                ;;
esac

exit 0
