#!/bin/bash 
# Builds the modules for all the kernels installed on the host
# parameters:
# 1 : destination directory
# 2 : package type (deb or rpm)

[ "$#" != "2" ] && echo "Not 2 args: $#" && exit 1

DEST_DIR=$1
PACKAGE_TYPE=$2

if [ "$PACKAGE_TYPE" = "rpm" ]; then
    which rpmbuild > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "'rpmbuild' utility hasn't been found. Please, install 'rpm-build' package before proceeding."
        exit 1
    fi
fi

cd `dirname "$0"`

#  Check destination directory:
if [ ! -d "$DEST_DIR" ]; then
    mkdir "$DEST_DIR"
fi

#  To make compiler happy:
mkdir -p lib; echo "clean:" > lib/Makefile
mkdir -p tests; echo "clean:" > tests/Makefile
mkdir -p utils; echo "clean:" > utils/Makefile

for KERN_DIR in /lib/modules/*/build ; do
    export KERN_VERS=`echo $KERN_DIR | cut -d"/" -f4`
    echo --- kernel $KERN_VERS --------

    if [ -d $KERN_DIR ]; then
        make -f Makefile.full KERNEL_VERS=$KERN_VERS modules_"$PACKAGE_TYPE"
        mv *."$PACKAGE_TYPE" "$DEST_DIR"
        make -f Makefile.full KERNEL_VERS=$KERN_VERS clean
    else     
        echo "NOTE: package 'kernel-devel-${KERN_VERS}' is absent in the system. Please, install it to build module for this kernel."
    fi

    echo --- kernel $KERN_VERS done ---
done

rm -rf lib tests utils
echo
echo "Done."
echo "Packages are in directory: '${DEST_DIR}':"
/bin/ls -1 ${DEST_DIR}/*.${PACKAGE_TYPE}
echo

exit 0

