#!/bin/sh
########################################################################
# Begin $rc_base/init.d/udev
#
# Description : Udev Boot Script
#
# Authors     : Based on Open Suse Udev Rules
#               kay.sievers@suse.de
#
# Adapted to  : Jim Gifford
# LFS	      : Alexander E. Patrakov
#
# Version     : 00.00
#
# Notes       :
#
########################################################################

. /etc/sysconfig/rc
. ${rc_functions}

trigger_device_events() {
	# generate events with the sysfs trigger
	list=$(echo /sys/bus/*/devices/*/uevent)
	list="$list $(echo /sys/class/*/*/uevent)"
	list="$list $(echo /sys/block/*/uevent /sys/block/*/*/uevent)"
	for i in $list; do
	    case "$i" in
		*/device/uevent|*\**)
		    # skip followed device symlinks
		    continue
		    ;;

		*/class/mem/*|*/class/tty/*)
		    first="$first $i"
		    ;;

		*/block/md*)
		    last="$last $i"
		    ;;

		*/*)
		    default="$default $i"
		    ;;
	    esac
	done

	# trigger the sorted events
	for i in $first $default $last; do
	    echo "add" > "$i"
	done
}

case "$1" in
    start)
	boot_mesg "Creating /dev in tmpfs..."
	mount -n -t tmpfs tmpfs /dev -o mode=755
	evaluate_retval

	boot_mesg "Copying static entries..."
	cp -ar /lib/udev/devices/* /dev
	evaluate_retval

	# disable hotplug helper, udevd listens to netlink
	if [ `cat /proc/sys/kernel/hotplug` ] ; then
	echo "" > /proc/sys/kernel/hotplug
	fi

	# start udevd
	boot_mesg "Starting udevd..."
	/sbin/udevd --daemon
	evaluate_retval

	# start coldplugging
	boot_mesg "Performing Coldplugging..."

	# unlikely, but we may be faster than the first event
	mkdir -p /dev/.udev/queue

	# configure all devices
	trigger_device_events

	# until we know how to do better, just wait for _all_ events to finish
	loop=300
	while test -d /dev/.udev/queue; do
	    sleep 0.1;
	    test "$loop" -gt 0 || break
	    loop=$(($loop - 1))
	done

	echo_ok
	;;

    stop)
	boot_mesg "Stopping udevd..."
	echo "/sbin/hotplug" > /proc/sys/kernel/hotplug
	killproc /sbin/udevd
	;;

    restart)
	boot_mesg "Restarting udevd..."
	killproc /sbin/udevd
	loadproc /sbin/udevd --daemon
	evaluate_retval
	;;

    status)
	statusproc /sbin/udevd
	;;

    reload)
	boot_mesg "Reloading udev rules..."
	udevcontrol reload_rules
	cp --preserve=all --recursive --update /lib/udev/devices/* /dev
	evaluate_retval
	;;

    force-reload)
	boot_mesg "Updating all available device nodes in /dev..."
	udevcontrol reload_rules
	rm -rf /dev/.udev /dev/disk
	cp --preserve=all --recursive --update /lib/udev/devices/* /dev
	trigger_device_events
	evaluate_retval
	;;

    *)
	echo "Usage: $0 {start|stop|restart|status|reload|force-reload}"
	exit 1
	;;
esac
