#!/bin/bash
#
# modprobe returns 255 when failed..
#MODCONF='/etc/modules.conf'
KV="$(uname -r)"
KV_MAJOR=`uname -r | cut -f1 -d "."`
KV_MINOR=`uname -r | cut -f2 -d "."`

ALLMOD_FILE="/lib/modules/$KV/modules.pcimap"
MODCONF="/etc/modules.autoload.d/kernel-${KV_MAJOR}.${KV_MINOR}"

function probe_module () {
   AL=`lsmod |grep "$*"`
   if [ "$AL" = "" ] ; then
      MOD=`echo "$*" | sed 's/-/_/'`
      AL=`lsmod | grep "$MOD"`
   fi
   if [ "$AL" = "" ] ; then
      modprobe $* > /dev/null 2>&1
      test $? = 0 && echo "Module $i loaded successful" && return 0
      echo "Cannot load module $i"
      return 1
   else
      echo "$* is already loaded"
      return 0
   fi
}

PCI_ID=`lspci -n |grep "Class 020" | awk '{print $4}'`
if [ "$PCI_ID" = "" ] ; then
   echo "No network card found"
#   sh /etc/vdr/plugins/admin/cfgnet.sh DISABLE
   exit 1
fi

VENDOR=`echo $PCI_ID | cut -f1 -d":"`
CARDID=`echo $PCI_ID | cut -f2 -d":"`


MODNAME=''
ALL_NETMODS=`cat $ALLMOD_FILE | grep "0x0000$VENDOR 0x0000$CARDID" | awk '{print $1}'`
for i in $ALL_NETMODS ; do
   echo " Testing $i"
   if probe_module $i ; then
      MODNAME=$i
      LOADED=`cat $MODCONF | grep "^$i$"`
      if [ "$LOADED" = "" ] ; then
         echo "$i" >> $MODCONF
         echo "Adding $i to $MODCONF"
      else
         echo "$* is already in $MODCONF"
      fi
   fi
done

#remove 8139cp if 8139too is already found
if [ `grep "^8139too" $MODCONF` ] && [ `grep "^8139cp" $MODCONF` ] ; then
   sed -i $MODCONF -e "/8139cp/d"
fi

if [ "$MODNAME" = "" ] ; then
   echo "No module for network card found"
#   exit 1
fi
exit 0
