#!/bin/sh
# API file systems that s6-linux-init leaves to the system, each only if the
# kernel supports it and nothing has mounted it yet. In a container the runtime
# provides them; there only /dev/shm, mqueue, /run/lock and the cgroup layout
# for nested container managers.
r=0
ct=
[ -s /run/init_env/container ] && ct=1

m() { # m FSTYPE SOURCE TARGET OPTIONS
	grep -qw "$1" /proc/filesystems 2>/dev/null || return 0
	mountpoint -q "$3" && return 0
	mkdir -p "$3" 2>/dev/null
	mount -t "$1" -o "$4" "$2" "$3" && return 0
	echo "mount-api: mounting $1 on $3 failed" >&2
	r=1
}

if [ -z "$ct" ]; then
	m proc proc /proc nosuid,nodev,noexec
	m sysfs sysfs /sys nosuid,nodev,noexec
	m devtmpfs devtmpfs /dev mode=0755,nosuid
	m devpts devpts /dev/pts mode=0620,gid=5,nosuid,noexec
	m securityfs securityfs /sys/kernel/security nosuid,nodev,noexec
	# options of systemd's unified hierarchy; kernels without them get a plain cgroup2
	if grep -qw cgroup2 /proc/filesystems && ! mountpoint -q /sys/fs/cgroup; then
		mount -t cgroup2 -o nosuid,nodev,noexec,nsdelegate,memory_recursiveprot cgroup2 /sys/fs/cgroup 2>/dev/null ||
			m cgroup2 cgroup2 /sys/fs/cgroup nosuid,nodev,noexec
	fi
	[ -d /sys/firmware/efi ] && m efivarfs efivarfs /sys/firmware/efi/efivars nosuid,nodev,noexec
	m pstore pstore /sys/fs/pstore nosuid,nodev,noexec
fi
m tmpfs tmpfs /dev/shm mode=1777,nosuid,nodev
[ -d /proc/sys/fs/mqueue ] && m mqueue mqueue /dev/mqueue nosuid,nodev,noexec

mkdir -p /run/lock && chmod 1777 /run/lock || r=1

if [ -n "$ct" ]; then
	/usr/libexec/s6-order-debian/cgroup-nesting || r=1
fi
exit $r
