#!/bin/sh

allowed_modules()
{
	local line module

	while read line; do {
		set -- $line
		module="$1"

		case "$module" in
			# enforced blacklist
			ipt_REJECT|nf_nat_ftp|nf_nat_irc|nf_conntrack_irc|nf_conntrack_ftp)
			;;
			*)		# modules: used now
				echo -n "${module}*|"
			;;
		esac
	} done </proc/modules

	echo -n "diag|switch-*"		# enforced whitelist
}

output_new_function()
{
	echo
	echo "load_modules()	# patched from $0"
	echo "{"
	echo "	local line file t1 t2 duration trash list_unload_later list_reverse kmodule"
	echo
	echo "	read t1 trash </proc/uptime"
	echo
	echo '	while [ -n "$1" ]; do {'
	echo '		file="$1"'
	echo "		shift"
	echo
	echo '		line="$( cat "$file" )"'
	echo '		test ${#line} -eq 0 && return'
	echo
	echo "		while read line; do {"
	echo '			case "$line" in'
	echo "				$( allowed_modules ))"
	echo '					echo >>/tmp/KMODULE.action "insmod $line"'
	echo '					insmod $line'
	echo
	echo '					case "$line" in'
	echo '						diag|switch-*)'
	echo '							# without parameters'
	echo '							echo >>/tmp/KMODULE.action "# later: rmmod ${line/ */}"'
	echo '							list_unload_later="$list_unload_later ${line/ */}'
	echo '						;;'
	echo '					esac'
	echo "				;;"
	echo "				*)"
	echo '					echo >>/tmp/KMODULE.action "# $line"'
	echo "				;;"
	echo "			esac"
	echo '		} done <"$file"'
	echo "	} done"
	echo
	echo '	for kmodule in $list_unload_later; do list_reverse="$kmodule $list_reverse"; done'
	echo '	for kmodule in $list_reverse; do {'
	echo '		echo >>/tmp/KMODULE.action "rmmod $kmodule"'
	echo '		rmmod $kmodule'
	echo '	} done'
	echo "}"
	echo
	echo '	read t2 trash </proc/uptime; duration=$(( ${t2//./} - ${t1//./} ))'
	echo '	logger -s "load_modules() done in $(( $duration / 100 )).$(( $duration % 100 )) sec"'
	echo "}"
}

grep -q ^"load_modules()	# patched" "/etc/functions.sh" || {
	output_new_function >>"/etc/functions.sh"
}
