#!/bin/sh

# Usage: modload [force]

TMPFILE=/tmp/.load.tmp.$$
MODFILE=/var/flash/freetz

trap "rm -f $TMPFILE" EXIT

[ -d "/tmp/flash" -a "$1" != "force" ] && exit 0

echo -n "Loading $MODFILE ... "
if cat $MODFILE > $TMPFILE 2> /dev/null; then
	if tar -xf $TMPFILE -C /tmp/ 2> /dev/null; then
		echo 'done.'
	else
		echo 'failed.'
		echo -n "Creating $MODFILE ... "
		mkdir -p /tmp/flash
		tar -cf $MODFILE -C /tmp flash
		echo 'done.'
	fi
else
	echo 'does not exist.'
	echo -n "Creating $MODFILE ... "
	mkdir -p /tmp/flash
	tar -cf $MODFILE -C /tmp flash
	echo 'done.'
fi
[ -d /tmp/flash/mod ] || mkdir -p /tmp/flash/mod

# Symlink files (of specific type) into the /mod tree
# $1    - file type (as in the shell command 'test')
# $2..n - files to symlink (absolute paths are expected)
lnmod() {
	local test="$1" file
	shift
	for file in "$@"; do
		if [ "$test" "$file" -a ! -e "/mod${file}" ]; then
			ln -s "$file" "/mod${file}"
		fi
	done
}

echo -n 'Loading users, groups and passwords ... '
/usr/bin/modusers load
echo 'done.'

echo -n 'Loading hosts ... '
/usr/bin/modhosts load
echo 'done.'

echo -n 'Loading config ... '
for pkg in $(cat /mod/etc/static.pkg 2>/dev/null) avm; do
	[ -e "/mod/pkg/$pkg" ] || ln -s / "/mod/pkg/$pkg"
	lnmod -d "/etc/default.$pkg"
	lnmod -d "/usr/lib/cgi-bin/$pkg"
	lnmod -x "/usr/lib/cgi-bin/$pkg.cgi"
	lnmod -x "/etc/init.d/rc.$pkg"
	lnmod -x $(ls /etc/init.d/rc.$pkg.* 2>/dev/null)
	[ -r "/mod/etc/default.$pkg/$pkg.cfg" ] && /usr/bin/modconf load "$pkg"
done
/usr/bin/modconf load avm
echo 'done.'

echo -n 'Loading modules ... '
for MODULE in fat vfat  mbcache ext2  jbd ext3  crc16 jbd2 ext4  reiserfs  nls_utf8 hfsplus  ipv6; do
	[ -e /lib/modules/$(uname -r)/kernel/*/*/${MODULE}.ko ] && modprobe $MODULE
done
if [ -r /tmp/flash/mod/modules ]; then
	grep -v "^ *#" /tmp/flash/mod/modules | while read -r module; do
		[ -n "$module" ] && modprobe ${module%.ko}
	done
fi
echo 'done.'

exit 0
