#!/bin/sh
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL
PATH=$PATH:/sbin:/bin:/usr/sbin:/usr/sbin

# Load the network device modules defined in /etc/modules in network initrd
# This code is from Debian Sarge /etc/init.d/modutils
# Loop over every line in /etc/modules.
echo "Loading the module from /etc/modules if assigned and exists..."
(cat /etc/modules; echo) | # make sure there is a LF at the end
while read module args; do
  case "$module" in
  	\#*|"") continue ;;
  esac
  echo -n "$module "
  modprobe $module $args 2>/dev/null
done

# Wait for 1 sec so that /proc or /sys is ready
sleep 1
# Detect and load the network devices
NIC_MOD="$(scan_pci)"
rc=$?
if [ "$rc" -eq 0 ]; then
  echo "The detected modules for hardware: $NIC_MOD. Try to load them..."
  for mod in $NIC_MOD; do
    modprobe $mod 2>/dev/null
  done
fi
# From Linux kernel 3.7 or later, no more modules.pcimap, so the above "scan_pci" method will fail, so we can use modules.alias
# Ref: http://comments.gmane.org/gmane.linux.kernel.pci/21211
if [ -d /sys/bus/pci/devices ]; then
  echo "Dir /sys/bus/pci/devices found. Try to load modules based on modules.alias..."
  # Due to older version of modprobe, like module-init-tools (3.9) (it still has modules.pcimap) on CentOS 6 does not support option "-R". 
  # Therefore we have to suppress the error messages.
  pic_list="$(cat /sys/bus/pci/devices/*/modalias 2>/dev/null | sort | uniq)"
  mod_list=""
  for i in $pic_list; do
    imod="$(modprobe -R $i 2>/dev/null)"
    imod="$(echo $imod)"  # make it 1 line.
    if [ -n "$imod" ]; then
      mod_list="$mod_list $imod"
    fi
  done
  echo "Loading these modules: $mod_list"
  for i in $mod_list; do
    modprobe $i
  done
fi
# Wait for 1 sec so that device is up
sleep 1
netdevices="$(get-nic-devs)"
if [ -z "$netdevices" ]; then
  kernel_ver=`uname -r`
  echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
  echo "The driver of network card is NOT found!"
  echo "Is this kernel $kernel_ver too old so it does not support this network card ?"
  echo "Without network card driver, we can NOT go on!"
  echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
  echo "Now enter shell to debug..."
  /bin/sh
fi

# nfs.o depends on sunrpc, lockd
modprobe nfs

# Always require af_packet for udhcpc if af_packet is not builtin.
# Normally, for RedHat-like, it's builtin. For Debian-like, it's a module.
# Anyway, we just test before do it.
if modprobe -n af_packet 2>/dev/null; then
  modprobe af_packet
fi
