#!/bin/bash
# Very dirty script to update all module-assistant managed modules on bootup.
# Released under the GPLv2 or later. You can find a copy of the license at http://www.gnu.org/licenses/gpl.txt
# (C) 2008 Fabio Rosciano

# First things first, let's get a list of installed kernels on the system. I take only the part that will be used in the generation of the modules package, not the actual version.

INSTALLED_KERNELS=`dpkg -l linux-image-2.6.* | grep ^ii | awk 'BEGIN { FS=" " } { print $2}' | sed 's/linux-image-//g'`

# Now let's get a list of all m-a-izable packages and their versions. They are stored in the format PACKAGE_NAME*PACKAGE_VERSION

MAIZABLE_PACKAGES=`dpkg -l *-source | grep ^ii | awk 'BEGIN { FS=" " } { print $2 "*" $3}' | sed 's/-source//g' | sed 's/-modules//g' | sed 's/-kernel//g'`

# It's time to check whether all m-a-ized packages are installed already. If not, they are created and installed automagically thanks to m-a.

for CHOSEN_KERNEL in ${INSTALLED_KERNELS[@]}; do

# Let's find out which architecture is this machine using and extract the version numbers of the installed kernels

ARCH=`dpkg --print-architecture`

KERNEL_VERSION=`echo $CHOSEN_KERNEL | sed 's/-$ARCH//g'`

	for MODULE_PACKAGE in ${MAIZABLE_PACKAGES[@]}; do
		
		# Let's define a couple of variables to make it slightly more readable
		# PACKAGE_NAME is the variable containing the name of the m-a-izable package
		PACKAGE_NAME=`echo $MODULE_PACKAGE | awk 'BEGIN { FS="*"} { print $1 }'`
		# PACKAGE_PATTERN is the variable containing the pattern of the m-a-izable package
		PACKAGE_PATTERN=`echo $MODULE_PACKAGE | awk 'BEGIN { FS="*"} { print $1 "*"}'`
		# PACKAGE_VERSION is the variable containing the version of the installed sources
		PACKAGE_VERSION=`echo $MODULE_PACKAGE | awk 'BEGIN { FS="*"} { print $2 "+" }'`
		# This is dirrrrty: If the package is installed, this returns "ii". If not, it returns nothing. I smell bugs here.
		INSTALLATION_CHECK=`dpkg -l $(echo $MODULE_PACKAGE | awk 'BEGIN { FS="*"} { print $1 "*"}') | grep $(echo $MODULE_PACKAGE | awk 'BEGIN { FS="*"} { print $2 "+" }') | grep $KERNEL_VERSION | grep ^ii | awk 'BEGIN { FS=" "} { print $1}'`

		if [ "$INSTALLATION_CHECK" == "ii" ]; then
			echo "Modules for $PACKAGE_NAME on kernel $CHOSEN_KERNEL are installed"
		else
			m-a prepare $PACKAGE_NAME
			m-a a-i -l $CHOSEN_KERNEL $PACKAGE_NAME
		fi

	done

done

# It should be done. If not, horrible things must have happened.

echo "All modules installed for all kernels. If something is wrong, please refer to the documentation of module-assistant"

exit

