#!/usr/sbin/openrc-run
### BEGIN INIT INFO
# Provides:          mountdevsubfs
# Required-Start:    mountkernfs
# Required-Stop:
# Default-Start:     S
# Default-Stop:
# Short-Description: Mount special file systems under /dev
# Description:       Mount the special file systems under /dev to make
#                    the full system ready for use.
### END INIT INFO

description="Mount special file systems under /dev."
extra_started_commands="reload"

depend()
{
	need mountkernfs.sh
	keyword -docker -podman -lxc -prefix -systemd-nspawn -vserver -wsl
	provide mountdevsubfs
}

TTYGRP=5
TTYMODE=620
[ -f /etc/default/devpts ] && . /etc/default/devpts

KERNEL="$(uname -s)"

. /lib/init/vars.sh
. /lib/init/tmpfs.sh
. /lib/init/mount-functions.sh

trylink() {
	test -h "/dev/$1" || test -d "/dev/$1" || ln -s -- "$2" "/dev/$1" || {
		ewarn "unable to ensure link /dev/$1 -> $2"
		ls -lad "/dev/$1"
	} >&2
}

mount_filesystems() {
	MNTMODE="$1"

	trylink fd /proc/self/fd
	trylink stdin fd/0
	trylink stdout fd/1
	trylink stderr fd/2
	mount_shm "$MNTMODE"

	if [ "$KERNEL" = Linux ]; then
		if [ ! -d /dev/pts ]; then
			mkdir --mode=755 /dev/pts
			[ -x /sbin/restorecon ] && /sbin/restorecon /dev/pts
		fi
		domount "$MNTMODE" devpts "" /dev/pts devpts "-onoexec,nosuid,gid=$TTYGRP,mode=$TTYMODE"
	fi
}

start()
{
	mount_filesystems mount_noupdate
	return 0
}

reload()
{
	mount_filesystems remount
	return 0
}

stop()
{
	return 0
}
