#!/bin/sh

get_device_id_table()
{
   case "$1" in
      *.ko.xz)
         xzcat "$1" ;;
      *)
         cat "$1" ;;
   esac | strings \
      | sed -n '/nNIBDS100_beginDeviceIDTable/,/nNIBDS100_endDeviceIDTable/p' \
      | grep -v "nNIBDS100_\(begin\|end\)DeviceIDTable"
}

matchedRank=254
matchedModule=""

directoryList="\
   /lib/modules/$(uname -r)/extra \
   /lib/modules/$(uname -r)/kernel/extra \
   /lib/modules/$(uname -r)/kernel/natinst \
   /lib/modules/$(uname -r)/updates \
"
directoryList=$(ls -d $directoryList 2>/dev/null)
moduleList=$(find $directoryList -name '*.ko' -or -name '*.ko.xz')
[ "$moduleList" = "" ] && exit 254

for module in $moduleList; do
   id_table=$(get_device_id_table "$module")
   if [ "$id_table" != "" ]; then
      rank=0
      for arg in "$@"; do
         if echo "$id_table" | grep -q "$arg"; then
            if [ $rank -lt $matchedRank ]; then
               matchedRank=$rank
               matchedModule="$(basename $module .ko)"
               matchedModule="$(basename $matchedModule .ko.xz)"
               [ $matchedRank = 0 ] && break
            fi
         fi
         rank=`expr $rank + 1`
      done
      [ $matchedRank = 0 ] && break
   fi
done

if [ "$matchedModule" != "" ]; then
   modprobe "$matchedModule"
   [ $? != 0 ] && exit 255
fi
exit $matchedRank
