#!/bin/sh
#
# (C) Copyright 1994  Mike Jagdis (jaggy@purplet.demon.co.uk)
#

. /etc/init.d/LIB
insmod=`pathof insmod /sbin:/etc:/bin:/usr/sbin:/usr/etc:/usr/bin`

# Where to look for loadable kernel modules. This should be set in an
# /etc/default file perhaps?
MODPATH=/boot:/boot/modules:/boot/subsystems:/boot/fs:/boot/drivers

# Process the load=... and noload=... boot line options (which are now
# in the environment) updating the /etc/default/modules file and
# creating a list of modules to be loaded now.
modlist=`echo $use_escapes "load $load\nnoload $noload" | tr ',' ' ' | awk '
$1 == "load" {
	for (i=2; i<=NF; i++) {
		mod[$i] = "Y"
	}
}

$1 == "noload" {
	for (i=2; i<=NF; i++) {
		mod[$i] = "N"
	}
}

END {
	# Generate the list of modules to load and create a new version
	# of the /etc/default/modules file.
	use = ""
	printf "" > "/etc/default/n_modules"
	while (getline it < "/etc/default/modules") {
		if (it !~ /^[ 	]*(Y|N|y|n)[ 	]+/) {
			print it >> "/etc/default/n_modules"
		} else {
			split(it, f)
			if (f[2] in mod) {
				if (mod[f[2]] == "Y") {
					sub(f[1], "Y", it)
					use = use " " f[2]
					mod[f[2]] = " "
				} else if (mod[f[2]] == "N") {
					sub(f[1], "N", it)
				}
			} else if (f[1] ~ /Y|y/) {
				use = use " " f[2]
			}
			print it >> "/etc/default/n_modules"
		}
	}

	# Replace the old /etc/default/modules file with the new
	system("rm -f /etc/default/modules; mv /etc/default/n_modules /etc/default/modules")

	# If there is anything left that we havent handled well
	# tag them on the end of the list in the order they were
	# specified.
	for (i in mod) {
		if (mod[i] == "Y")
			use = use " " i
	}

	# Print the list of modules to be loaded to stdout
	print use
}
'`

if [ -n "$modlist" ]; then
	if [ -z "$insmod" ]; then
		echo "WARNING: insmod not found."
		echo "WARNING: you must install the modutils package to use loadable modules."
	else
		echo $use_escapes "Loading modules:\c"
		KERNVRSN=`uname -r`
		for mod in $modlist
		do
			modpath=`pathof $mod.$KERNVRSN $MODPATH`
			if [ -z "$modpath" ]; then
				modpath=`pathof $mod $MODPATH`
			fi
			if [ -z "$modpath" ]; then
				modpath=`pathof $mod.o $MODPATH`
			fi
			if [ -z "$modpath" ]; then
				echo $use_escapes "\nWARNING: module $mod not found"
			else
				echo $use_escapes " $mod\c"
				$insmod $modpath
			fi
		done
		echo
	fi
fi
