#!/sbin/openrc-run

command="/usr/sbin/gardendevd"
command_args="-C ${gardendev_opts}"
command_background=yes
pidfile=/run/gardendevd.pid
description="gardendev manages device metadata, symbolic links, and tags in /dev"
extra_started_commands="reload"
description_reload="Reload the udev rules and databases"

depend() {
	need sysfs dev-mount
	use mdevd
	before checkfs fsck
	keyword -containers
}

start_pre() {
	if ! grep -qs devtmpfs /proc/filesystems; then
		eerror "CONFIG_DEVTMPFS=y is required in your kernel configuration"
		eerror "for gardendevd to run successfully."
		return 1
	fi

	if ! mountinfo -q -f devtmpfs /dev; then
		eerror "gardendevd requires /dev to be a mounted devtmpfs."
		eerror "Please reconfigure your system."
		return 1
	fi

	if [ ! -e /proc/net/unix ]; then
		if ! modprobe unix; then
			eerror "Cannot load the unix domain socket module"
			return 1
		fi
	fi

	if [ -e /proc/sys/kernel/hotplug ]; then
		echo "" >/proc/sys/kernel/hotplug
	fi

	mkdir -p /run/udev/data /run/udev/tags /run/udev/links /run/udev/rules.d \
		/run/gardendevd

	if yesno "${gardendev_debug:-NO}"; then
		command_args="${command_args} -v debug"
		error_log="/run/udevdebug.log"
	fi

	return 0
}

stop() {
	ebegin "Stopping ${name:-$RC_SVCNAME}"
	gardendevctl control --exit ||
		start-stop-daemon --stop --exec "${command}" --pidfile "${pidfile}"
	eend $? "Failed to stop $RC_SVCNAME"
	[ $? -eq 0 ] && rm -f "${pidfile}"
}

reload() {
	ebegin "Reloading udev rules and databases"
	gardendevctl control --reload
	eend $?
}
