#!/bin/bash
# $Id: hotplug,v 1.8 2004/05/25 16:02:51 zoz Exp $
#
# In 2.5, both classes and busses can report hotplug events as part
# of the driver model core functionality.  Plus, /sys/$DEVPATH is
# available for scripting, as well as the $ACTION being reported.
#
# The kernel HOTPLUG configuration option needs to be enabled, and most
# device drivers will be compiled for MODULES (make allmod).
#

export LOGPID=$$

# The event recorder comes with package udev. If you like all events recorded
# then create a directory /events
if [ -x /sbin/hotplugeventrecorder ] ; then
    /sbin/hotplugeventrecorder $1 2>/dev/null
fi

SYSFS=needed
cd /etc/hotplug
. hotplug.functions

debug_mesg $ACTION $*
if [ -x /usr/bin/env ] ; then
	debug_mesg `/usr/bin/env`
fi

for a in `cat /proc/cmdline`; do
	case $a in
		NOHOTPLUG=*)
			eval "$a"
			;;
	esac
done
if [ -f /var/run/hotplug/ignore_nohotplug -a -n "$NOHOTPLUG" ] ; then
	debug_mesg "ignoring NOHOTPLUG=$NOHOTPLUG, because started manually"
	unset NOHOTPLUG
fi

AGENT=/etc/hotplug/$1.agent
if [ -n "$NOHOTPLUG" ] ; then
	if [ "$NOHOTPLUG" = udev-only ] ; then
		debug_mesg "Call only udev due to NOHOTPLUG=$NOHOTPLUG"
		AGENT=
	else
		debug_mesg "Hotplugging is disabled due to NOHOTPLUG=$NOHOTPLUG"
		exit 0
	fi
fi

# Check if this type of events should be handled at all
#
for SKIP in $HOTPLUG_SKIP_EVENTS _dont_skip_; do
	test $1 = $SKIP && break
done
if [ "$SKIP" != _dont_skip_ ] ; then
	debug_mesg "Events of type '$1' are skipped"
	exit 0
fi

# Delegate event handling:
#   /sbin/hotplug FOO ..args.. ==> /etc/hotplug/FOO.agent ..args..
#
if [ -x $AGENT ]; then
    # debug_mesg "invoke '$AGENT $@'"
    exec $AGENT $@
    mesg "couldn't exec $AGENT"
    exit 1
fi

UDEV_AGENT=/etc/hotplug/generic_udev.agent
for WAIT in 0 1 2 3 4 5; do
if [ -x $UDEV_AGENT -a -f $SYSFS/$DEVPATH/dev ]; then
    debug_mesg "invoke '$UDEV_AGENT $@' after $WAIT seconds"
    exec $UDEV_AGENT $@
    mesg "couldn't exec $UDEV_AGENT"
    exit 1
fi
sleep 1
done

debug_mesg "no runnable $AGENT is installed"

exit 1
