#!/bin/bash

# This code is based on eeprom_fix_82574_or_82583/fixeep-82574_83.sh, available at the e1000e
# driver sourceforge page [1], and follows the original source code licensing terms.
#
# [1] http://sourceforge.net/projects/e1000/files/e1000e%20stable/eeprom_fix_82574_or_82583/

export PATH="$PATH:/usr/sbin:/sbin:/bin"

PROGNAME=`basename $0`

dolog()
{
    echo "$PROGNAME: $@"
    logger -t "$PROGNAME" "$@"
}

epprom_fix="n"
failed_fix="n"

for iface in eth0 eth1
do
    if ! ifconfig ${iface} >/dev/null 2>/dev/null
    then
        dolog "${iface}: interface does not exist, skipping..."
        continue
    fi

    bdf=$(ethtool -i ${iface} | grep "bus-info:" | awk '{print $2}')

    if [ "$bdf" = "" ]
    then
        dolog "${iface}: no bus info, virtual interface?"
        continue
    fi

    dev=$(lspci -s $bdf -x | grep "00: 86 80" | awk '{print "0x"$5$4$3$2}')

    case $dev in
        0x10d38086)
            dolog "${iface}: is a \"82574L Gigabit Network Connection\""
        ;;
        0x10f68086)
            dolog "${iface}: is a \"82574L Gigabit Network Connection\""
        ;;
        0x150c8086)
            dolog "${iface}: is a \"82583V Gigabit Network Connection\""
        ;;
        *)
            dolog "${iface}: no appropriate hardware found for this fixup"
            continue
        ;;
    esac

    dolog "${iface}: this fixup is applicable, checking eeprom values"

    var=$(ethtool -e ${iface} | grep 0x0010 | awk '{print $16}')
    new=$(echo ${var:0:1}`echo ${var:1} | tr '014589bc' '2367abef'`)

    if [ ${var:0:1}${var:1} == $new ]; then
        dolog "${iface}: your eeprom is up to date, no changes were made"
        continue
    fi

    dolog "${iface}: running ethtool, magic $dev offset 0x1e value 0x$new"
    if ethtool -E ${iface} magic $dev offset 0x1e value 0x$new 
    then
        dolog "${iface}: update succesful!"
        eeprom_fix="y"
    else
        dolog "${iface}: ERROR: ethtool returned non-zero result code!"
        failed_fix="y"
    fi
done

# if at least one was fixed, reboot is needed
[ "$eeprom_fix" = "y" ] && exit 1

# if at least one failed, use error code
[ "$failed_fix" = "y" ] && exit 2

# nothing was changed
exit 0
