#!/usr/bin/env bash

check_cgroups_memory() {
	task_begin "Checking memory cgroups";
	
	cgroups_enabled="$(awk '/memory/ { print $2 }' < /proc/cgroups)";
	
	if [[ "${cgroups_enabled}" -ne 0 ]]; then
		echo ">>> memory cgroups already enabled";
		return 0;
	fi
	
	
	filepath_cmdline="/boot/cmdline.txt";
	if [[ ! -e "${filepath_cmdline}" ]]; then
		filepath_cmdline="/boot/firmware/cmdline.txt";
	fi
	if [[ ! -e "${filepath_cmdline}" ]]; then
		echo ">>> Failed to find cmdline.txt; can't check for cgroups";
		return 1;
	fi
	
	if grep -q cgroup_enable=memory /boot/cmdline.txt; then
		echo ">>> memory cgroups already present in cmdline.txt, a reboot is required to apply the update";
		return 0;
	fi
	
	echo ">>> memory cgroups not present in cmdline.txt, enabling....";
	(tr -d '\n' <"${filepath_cmdline}" && echo " cgroup_enable=memory cgroup_memory=1") | sudo tee "${filepath_cmdline}.new";
	
	sudo mv "${filepath_cmdline}" "${filepath_cmdline}.old-$(date +"%Y-%m-%d")";
	sudo mv "${filepath_cmdline}.new" "${filepath_cmdline}";
	
	echo ">>> New contents of cmdline.txt:";
	cat "${filepath_cmdline}";
	echo ">>> A reboot is required to apply the changes.";
	
	task_end "$?" "Failed to check memory cgroups"
}