#!/bin/sh -e
#
# This is the update-modules script for Debian GNU/Linux.
# Copyright 1998-2001 Wichert Akkerman <wakkerma@debian.org>
# Copyright 2002 Marco d'Itri <md@linux.it>
# Licensed under the GNU GPL, version 2.

# when started from postinst update-modules.modutils could fail because
# of a custom configuration
if [ "$1" != nocompat ]; then
	[ -x /sbin/update-modules.modutils ] && /sbin/update-modules.modutils
fi

MODCONFFILE=/lib/modules/modprobe.conf
MODCONFDIR=/etc/modprobe.d

# reset the sorting order since we depend on it
export LC_COLLATE=C

archmodel() {
	local arch=$(uname -m)
      	case $arch in
	i[0-9]86)	arch=i386 ;;
	sun4u)		arch=sparc64 ;;
	arm*)		arch=arm ;;
	ppc)
		if [ -f /proc/cpuinfo ]; then
			model=$(sed -ne 's/^machine[[:space:]]*:[[:space:]]*//p' /proc/cpuinfo)
		else
			echo "/proc/cpuinfo does not exist, assuming generic powerpc system" >&2
		fi
		case "$model" in
			Amiga*) arch="powerpc.apus" ;;
			Power*) arch="powerpc.pmac" ;;
			*) arch="powerpc.generic" ;;
		esac
		;;
	m68k)
		if [ -f /proc/hardware ]; then
			model=$(sed -ne 's/^Model:[[:space:]]*//p' /proc/hardware)
		else
			echo "/proc/hardware does not exist, assuming generic m68k system" >&2
		fi
		case "$model" in
			Atari*) arch="m68k.atari" ;;
			Amiga*) arch="m68k.amiga" ;;
			Macintosh*) arch="m68k.mac" ;;
			Motorola*) arch="m68k.MVME" ;;
			*) arch="m68k.generic" ;;
		esac
		;;
	esac
	echo $arch
}

createfile() {
	cat <<EOF
# This file is automatically generated by update-modules, please do not
# edit it directly.
# If you want to change or add anything here please read /etc/modprobe.conf,
# the files in /etc/modprobe.d/ and the manpage for update-modules(8).
#
EOF
}

addfile() {
	local src="$1"

	printf "\n### update-modules: start processing $src\n"
	if [ -x "$src" ]; then
		if ! "$src"; then
			echo "Error while executing $src, aborting" >&2
			exit 1
		fi
	else
		cat "$src"
	fi
	printf "\n### update-modules: end processing $cfg\n"
}


model=$(archmodel)
oldmodel=$model

while [ ! -f $MODCONFDIR/arch/$model ]; do
	oldmodel=$model
	model=`echo $oldmodel | sed -e 's/\.[^.]\+//'`
	[ "$model" = "$oldmodel" ] && break
	echo "Configuration for $oldmodel not found, trying $model"
done

ARCHCONFFILE=arch/$model

if [ ! -f $MODCONFDIR/$ARCHCONFFILE ]; then
	echo "Architecture-specific modutils configuration not found"
	ARCHCONFFILE=/dev/null
fi

[ -e $MODCONFFILE ] && cp -f $MODCONFFILE $MODCONFFILE.old

MODCONFTMPFILE=$MODCONFFILE.tmp
createfile > $MODCONFTMPFILE

for cfg in $MODCONFDIR/$ARCHCONFFILE $MODCONFDIR/*; do
	# this check is needed to skip /etc/modutils/archs
	[ -d "$cfg" ] && continue
	if ! echo "$cfg" | grep -q '\(\.dpkg-[a-z]*\|~\|,v\)$'; then
		addfile "$cfg" >> $MODCONFTMPFILE
	fi
done

mv $MODCONFTMPFILE $MODCONFFILE

exit 0

