#!/bin/bash
# Steven Shiau <steven _at_ nchc org tw>
# License: GPL
# Description: To parse the /lib/modules/$KERNEL to get the modules for network
# Usage: $0 KERNEL_VERSION
# Ex: $0 2.6.8.1-25mdk

#
usage() {
 echo Usage: $0 [OPTION] KERNEL_VERSION
 echo "OPTION:"
 echo " -p|--prefix PATH   Add the prefix PATH so it will use the modules.deps  in PATH/lib/modules/."
 echo " -k|--kernel-ver KVER   Use kernel version KVER for DRBL client."
 echo " -h|--help          Show the usage info."
 echo "Ex: $0 2.6.8.1-25mdk"
 echo "Note! This program only works for kernel version >= 2.6"
}

while [ $# -gt 0 ]; do
  case "$1" in
    -p|--prefix)
            shift; 
            # skip the -xx option, in case 
            [ -z "$(echo $1 |grep ^-.)" ] && PREFIX="$1"
            shift;;
    -k|--kernel-ver)
            shift; 
            # skip the -xx option, in case 
            [ -z "$(echo $1 |grep ^-.)" ] && kver="$1"
            shift;;
    -h|--help)
	    usage >& 2
	    shift;;
    -*)	    echo "${0}: ${1}: invalid option" >&2
	    usage >& 2
	    exit 2 ;;
    *)	    break ;;
  esac
done

[ -z "$kver" ] && exit 1
net_mod_path="/lib/modules/$kver/kernel/drivers/net"
net_mod_reg="^$net_mod_path/.*\.ko(\.gz)*:"
exclude_list="appletalk fc hamradio irda pcmcia tokenring wan wireless wireless_old irda"
for ie in $exclude_list; do
  exclude_opt="$exclude_opt|$net_mod_path/$ie"
done
exclude_opt="$(echo $exclude_opt | sed -e "s/^|//g")"

# skip those duplicate modules, and we need to strip the leading "/" so that
# we get the path is relative path like:
# kernel/drivers/net/8139too.ko
# Then it's easier for us to copy them.
# Note!!! sed -e "s|^/lib/modules/$kver/||", the / after $kver is very important
# Do ***NOT*** remove that!
(
  # get the network card modules
  grep -E "$net_mod_reg" $PREFIX/lib/modules/$kver/modules.dep | grep -vE "($exclude_opt)" | awk -F":" '{print $1}' 

  # get those depended modules
  grep -E "$net_mod_reg" $PREFIX/lib/modules/$kver/modules.dep | grep -vE "($exclude_opt)" | awk -F":" '{print $2}' | awk -F' ' '{for (i = 1; i <= NF; i = i + 1) print $i}'
) | sort | uniq | sed -e "s|^/lib/modules/$kver/||"
