#!/bin/sh
#
# chkconfig: 2345 01 99
# description: Starts nic autodetection script

is_active_traffic()
{
    sleep 5
    grep $1 /proc/net/dev|while read ifname rbytes rpackets skip skip skip skip skip skip tbytes tpackets other; do
        [ $rbytes -ne 0 -o $rpackets -ne 0 ]
    done
}

is_active()
{
    rc=1
    ifconfig $1 up
    if /usr/sbin/ethtool $1 2>/dev/null | grep "Link detected: yes" >/dev/null 2>&1 ; then
        echo "$1 is active ethtool"
        rc=0
    elif /usr/sbin/ethtool $1 2>/dev/null | grep "Link detected: no" >/dev/null 2>&1 ; then
        echo "$1 isn't active ethtool"
        rc=1
    elif is_active_traffic $1 ; then
        echo "$1 is active traffic"
        rc=0
    fi
    ifconfig $1 down
    return $rc
}

start() {

PCILIST=/etc/pcilist
MODTMP=/tmp/modules.conf.tmp
X=0
fname="/etc/sysconfig/network-scripts/ifcfg-eth"

# save non-aliases parts of mdules.conf
egrep -v '^[[:blank:]]*alias[[:blank:]]*eth[0-9]' /etc/modules.conf > $MODTMP

# Detectiong NICs
lspci -n | while read Num CLASS Class IdPCI Other; do
	[ $Class = 0200: ] || continue
	IdPCI=`echo $IdPCI|sed -e 's/://'`
	Row=`sed -n "/^$IdPCI/p" $PCILIST`
	if [ "$Row" ]; then #Device found in pci list
		set $Row
		Module=`echo $2|sed -e 's/\"//g'`
		[ "$Module" = unknown -o "$Module" = ignore ] && continue
		case $Module in
			# Gigabit cards	
			slicatcp)	weight=100
					;;
			e1000)		weight=99
					;;
			acenic)		weight=98
					;;
			sk98lin)	weight=97
					;;
			yellowfin)	weight=96
					;;
			ns83820)	weight=95
					;;
			# 100 Mb cards
			eepro100)	weight=89
					;;
			3c90x)		weight=88
					;;
			3c59x)		weight=87
					;;
			tulip)		weight=86
					;;
			*)		weight=0
					;;
		esac		
		echo $weight $Module
	fi
done | sort -rnk1 | while read weight module; do
	egrep -q "$module" /proc/modules || /sbin/modprobe $module
	fn="${fname}$X"
	if [ -f "$fn" ] ; then
		AUTOCFG="no"
		. "$fn"
	else
		AUTOCFG="yes"
		echo -e "DEVICE=eth$X\nBOOTPROTO=dhcp\nIPADDR=\nNETMASK=\nBROADCAST=\nONBOOT=no\nAUTOCFG=yes\n" > "$fn"
	fi
	if [ $AUTOCFG = "yes" ] ; then 
		if is_active "eth$X" ; then
			subst "s/ONBOOT=.*/ONBOOT=yes/" "$fn"
		else
			subst "s/ONBOOT=.*/ONBOOT=no/" "$fn" 
		fi
	fi
	echo "alias eth$X $module" >> $MODTMP
	let X++
done

grep "ONBOOT=yes" ${fname}* >/dev/null 2>&1 || subst "s/ONBOOT=.*/ONBOOT=yes/" "${fname}0"

# Put generated modules.conf on place
mv $MODTMP /etc/modules.conf
depmod -A

}

case $1 in
		start) start
			;;
			*) echo "Usage: `basename $0` start"
			;;
esac		
