is_module_loaded()
{
	module=$1
        awk "BEGIN{x=1}(\$1 == \"$module\"){x=0;exit} END{exit x}" \
		/proc/modules 
}

unload_module()
{
	module=$1
	rmmod $module
}

#
# load_module(module,var)
#   module - the name of the module to load (should NOT end in .o)
#   var    - name of the _environment variable_ that contains the
#            the fully qualified path name to the module to load.
#            If the environment variable is not defined, the module
#            contained in the GFS-modules rpm is used.
# Example:
#  MODULE_POOL=/root/backup/modules/pool.o
#  load_module pool MODULE_POOL
#
# returns 0 if the module is already loaded or if it loaded successfully
# and returns 1 on failure
#
load_module()
{
	module=$1
	var=$2
	shift
	shift
	opts=$*

	is_module_loaded $module && return 0

	if ! insmod $module $opts > /dev/null 2>&1
	then
		mod=$(eval echo \$$var)

		if [ -z "$mod" ]
		then
			rpm=$( rpm -qa | grep GFS-modules )
			if [ $? -ne 0 ]
			then
				echo "unable to query GFS-modules rpm" >&2
				return 1
			fi

			for rpm1 in $rpm
			do
				if [ -z "$rpm2" ]
				then
					rpm2=$rpm1	
				else
					# multiple GFS rpms detected
					echo "unable to autodetect location for module \"$module\"" >&2
					echo "define $var in /etc/sysconfig/gfs or rerun \"depmod -ae\"" >&2
					return 1
				fi
			done

			mod=$( rpm -ql $rpm | grep /$module\\.o )
			if [ $? -ne 0 ]
			then
				echo "module '$module' not found" >&2
				return 1
			fi
		fi

		insmod -f "$mod" $opts || return 1
	fi

	return 0
}
