#!/bin/sh

MODULES="dahdi"
DAHDI_MODULES_FILE="/etc/dahdi/modules"

usage() {
	cat <<EOF
$0: loads / unloads DAHDI kernel modules

Usage: $0 <load|unload>

* load: Loads all modules listed in /etc/dahdi/modules (one per line)
* unload: Unloads the DAHDI modules (all the modules that are dependencies
  of $MODULES).
EOF
}

# recursively unload a module and its dependencies, if possible.
# where's modprobe -r when you need it?
# inputs: module to unload.
# returns: the result from
unload_module() {
	module="$1"
	line=`lsmod 2>/dev/null | grep "^$1 "`
	if [ "$line" = '' ]; then return; fi # module was not loaded

	set -- $line
	# $1: the original module, $2: size, $3: refcount, $4: deps list
	mods=`echo $4 | tr , ' '`
	ec_modules=""
	# xpp_usb keeps the xpds below busy if an xpp hardware is
	# connected. Hence must be removed before them:
	case "$module" in xpd_*) mods="xpp_usb $mods";; esac

	for mod in $mods; do
		case "$mod" in
		dahdi_echocan_*)
			ec_modules="$mod $ec_modules"
			;;
		*)
			# run in a subshell, so it won't step over our vars:
			(unload_module $mod)
			;;
		esac
	done
	# Now that all the other dependencies are unloaded, we can unload the
	# dahdi_echocan modules.  The drivers that register spans may keep
	# references on the echocan modules before they are unloaded.
	for mod in $ec_modules; do
		(unload_module $mod)
	done
	rmmod $module
}

unload_modules() {
	for module in "$@"; do
		unload_module $module
	done
}

load_modules() {
	modules=`sed -e 's/#.*$//' $DAHDI_MODULES_FILE 2>/dev/null`
	for line in $modules; do
		modprobe $line
	done
}

case "$1" in
	load) load_modules "$@";;
	unload) unload_modules $MODULES;;
	*) usage;;
esac
