#!/usr/sbin/openrc-run

description="hot-plug events dispatcher (eudev)"

command="/sbin/udevd"
command_args="--daemon"
pidfile="" # udevd --daemon manages itself; match by name/exec
name="udevd"

depend()
{
	need mountkernfs.sh
	before checkroot.sh
	# Stop before remounting root RO / final halt.
	after umountroot
	provide eudev udev
	keyword -docker -lxc -openvz -prefix -systemd-nspawn -vserver
}

extra_started_commands="reload"

# we need to unmount /dev/pts/ and remount it later over the devtmpfs
unmount_devpts() {
	if mountpoint -q /dev/pts/; then
		umount -n -l /dev/pts/
	fi

	if mountpoint -q /dev/shm/; then
		umount -n -l /dev/shm/
	fi
}

# mount a devtmpfs over /dev, if somebody did not already do it
mount_devtmpfs() {
	if grep -E -q "^[^[:space:]]+ /dev devtmpfs" /proc/mounts; then
		mount -n -o remount,nosuid,size=$tmpfs_size,mode=0755 -t devtmpfs devtmpfs /dev
		return 0
	fi

	if ! mount -n -o nosuid,size=$tmpfs_size,mode=0755 -t devtmpfs devtmpfs /dev; then
		eerror "eudev requires devtmpfs support, ${name} not started"
		return 1
	fi
	return 0
}

create_dev_makedev() {
	if [ -e /sbin/MAKEDEV ]; then
		ln -sf /sbin/MAKEDEV /dev/MAKEDEV
	else
		ln -sf /bin/true /dev/MAKEDEV
	fi
}

# shell version of /usr/bin/tty
my_tty() {
	[ -x /bin/readlink ] || return 0
	[ -e /proc/self/fd/0 ] || return 0
	readlink --silent /proc/self/fd/0 || true
}

warn_if_interactive() {
	if [ "$RUNLEVEL" = "S" ] && [ "$PREVLEVEL" = "N" ]; then
		return 0
	fi

	TTY=$(my_tty)
	if [ -z "$TTY" ] || [ "$TTY" = "/dev/console" ] || [ "$TTY" = "/dev/null" ]; then
		return 0
	fi

	ewarn "It has been detected that eudev was started from an interactive shell."
	ewarn "RUNNING THIS COMMAND IS HIGHLY DISCOURAGED! Waiting 60 seconds (^C to abort)."
	sleep 60
}

make_static_nodes() {
	[ -e /lib/modules/$(uname -r)/modules.devname ] || return 0
	[ -x /bin/kmod ] || return 0

	/bin/kmod static-nodes --format=tmpfiles --output=/proc/self/fd/1 | \
	while read type name mode uid gid age arg; do
		[ -e $name ] && continue
		case "$type" in
			c|b|c!|b!) mknod -m $mode $name $type $(echo $arg | sed 's/:/ /') ;;
			d|d!) mkdir $name ;;
			*) echo "unparseable line ($type $name $mode $uid $gid $age $arg)" >&2 ;;
		esac

		if [ -x /sbin/restorecon ]; then
			/sbin/restorecon $name
		fi
	done
}

tmpfs_size="10M"
[ -e /etc/udev/udev.conf ] && . /etc/udev/udev.conf

start_pre() {
	[ -x "$command" ] || return 0

	if [ ! -e /proc/filesystems ]; then
		eerror "eudev requires a mounted procfs, ${name} not started"
		return 1
	fi

	if ! grep -q '[[:space:]]devtmpfs$' /proc/filesystems; then
		eerror "eudev requires devtmpfs support, ${name} not started"
		return 1
	fi

	if [ ! -d /sys/class/ ]; then
		eerror "eudev requires a mounted sysfs, ${name} not started"
		return 1
	fi

	if [ -d /sys/class/mem/null ] && [ ! -L /sys/class/mem/null ] || \
	   [ -e /sys/block ] && [ ! -e /sys/class/block ]; then
		ewarn "CONFIG_SYSFS_DEPRECATED must not be selected"
		ewarn "Booting will continue in 30 seconds but many things will be broken"
		sleep 30
	fi
	return 0
}

start() {
	start_pre || return $?

	# System processes and/or kernel threads are surrounded by brackets: [...]
	if ! ps --no-headers --format args ax | egrep -q '^\['; then
		ewarn "eudev does not support containers, ${name} not started"
		return 0
	fi

	if [ ! -e "/run/udev/" ]; then
		warn_if_interactive
	fi

	if [ -w /sys/kernel/uevent_helper ]; then
		echo > /sys/kernel/uevent_helper
	fi

	if ! mountpoint -q /dev/; then
		unmount_devpts
		mount_devtmpfs || return 1
		[ -d /proc/1 ] || mount -n /proc
	fi

	make_static_nodes

	# clean up parts of the database created by the initramfs udev
	udevadm info --cleanup-db

	# set the SELinux context for devices created in the initramfs
	[ -x /sbin/restorecon ] && /sbin/restorecon -R /dev

	ebegin "Starting ${description}"
	# OpenRC start-stop-daemon: no --quiet/--oknodo
	if ! start-stop-daemon -S -n "$name" -x "$command" -- $command_args; then
		ewarn "udevd start failed; waiting 15 seconds and trying to continue anyway"
		sleep 15
	fi
	eend 0

	ebegin "Synthesizing the initial hotplug events (subsystems)"
	udevadm trigger --type=subsystems --action=add
	eend $?

	ebegin "Synthesizing the initial hotplug events (devices)"
	udevadm trigger --type=devices --action=add
	eend $?

	create_dev_makedev

	# wait for the udevd children to finish
	ebegin "Waiting for /dev to be fully populated"
	if udevadm settle; then
		eend 0
	else
		eend 0 "timeout"
	fi
	return 0
}

stop() {
	ebegin "Stopping ${description}"
	start-stop-daemon -K -n "$name" -x "$command" -R TERM/5
	eend $?
}

reload() {
	udevadm control --reload-rules
}
