#!/bin/sh
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL
# Description: find the modules for PCI devices.
# This program will try to match 2 tables, the first is from hwdata (kudzu uses that, too). If not found, try to match the table from kernel "modules.pcimap".
# The "modules.pcimap" will be put by program mkpxeinitrd-net when it is run with kernel.

# 
PATH=/sbin/:/usr/sbin:/bin:/usr/bin:

pcitable_dir=$1
if [ -f $pcitable_dir/pcitable ]; then
  pcitable_hwdata="$pcitable_dir/pcitable"
elif [ -f /etc/pcitable ]; then
  pcitable_hwdata="/etc/pcitable"
else 
  pcitable_hwdata="/usr/share/hwdata/pcitable"
fi
# pcitable_kernel is gotten from kernel
pcitable_kernel="/etc/modules.pcimap"

if [ ! -f $pcitable_hwdata ]; then
   echo "File \"pcitable\" not found!"
   echo "Usage: $0 pcitable_path"
   exit 1 
fi
# For old "lspci -n" output, the results are like:
# 00:00.0 Class 0600: 8086:2550 (rev 03)
# 00:00.1 Class ff00: 8086:2551 (rev 03)
# 00:01.0 Class 0604: 8086:2552 (rev 03)
# Newer:
# 00:00.0 0600: 8086:7190 (rev 01)
# 00:01.0 0604: 8086:7191 (rev 01)
# 00:07.0 0601: 8086:7110 (rev 08)

# We want the output format as: 0x8086:0x7190
PCI_ID="$(LC_ALL=C lspci -n | sed -e "s/Class //g" | cut -d" " -f3 | cut -d":" -f1-2 | sed -e "s/^/0x/" -e "s/:/:0x/")"

mod_found=""
for d in $PCI_ID; do
  # We will try to find the NIC module from (1) the hwdata pcitable and (2) the table from kernel, if both are found with different modules, we will use both.
  # Part I: try to find it in hwdata pcitable
  if [ -f "$pcitable_hwdata" ]; then
    # note! It's tab
    d2=$(echo $d | sed -e "s/:/	/")
    mtmp=$(grep "$d2" $pcitable_hwdata | sort | uniq | cut -f3 | sed -e "s/\"//g")
    for im in $mtmp; do
      if [ -n "$im" -a "$im" != "unknown"  -a -z "$(echo $mod_found | grep -E "\<$im\>")" ]; then
        mod_found="$mod_found $im"
      fi
    done
  fi
  # part II: Try to find in the table from kernel
  if [ -f "$pcitable_kernel" ]; then
    # The table in pcitable_kernel with prefix 0x0000 like
    # eepro100 0x00008086 0x00005201
    # Note! It's space now, not tab.
    d3=$(echo $d | sed -e "s/:/ /" -e "s/0x/0x0000/g")
    mtmp=$(grep "$d3" $pcitable_kernel | sort | uniq | cut -d" " -f1)
    for im in $mtmp; do
      if [ -n "$im" -a "$im" != "unknown"  -a -z "$(echo $mod_found | grep -E "\<$im\>")" ]; then
        mod_found="$mod_found $im"
      fi
    done
  fi
done
if [ -n "$mod_found" ]; then
  echo "$mod_found"
  exit 0
else
  echo "Not any known PCI device is found by scan_pic. Another method will be used later..."
  exit 1
fi
