#!/bin/sh
# This here is an ungly hack, that should not be needed
# Issues only with some TX6UL if network cable is connected after bootup

tx6ul_eth0_int() {
    awk '/phy_interrupt|2188000.ethernet-1:00/{print $2}' /proc/interrupts
}

energy_detect_disabled() {
    find '/sys/class/net/eth0/device/of_node/' -name '*disable-energy-detect' \
    | grep -Fq -- 'disable-energy-detect'
}

tx6ul_eth0_needFix() {
    # Cable never connected Unknown! will be shown
    ethtool eth0 | grep -Fq -- 'Unknown!' && return 0

    ethtool eth0 | grep -Fq -- 'Link detected: no' || return 1
    c1="$(tx6ul_eth0_int)"
    [ -z "$c1" ] && return 1
    sleep 3
    ethtool eth0 | grep -Fq -- 'Link detected: no' || return 1
    c2="$(tx6ul_eth0_int)"
    [ -z "$c2" ] && return 1

    # On working devices: interrupts increase if cable is not connected
    [ "$c1" = "$c2" ] || return 1
    return 0
}

start() {
    # Workaround for some weird software issue?
    # Seems to be working well with disable-energy-detect
    energy_detect_disabled && return 0
    # Issues only with some TX6UL if network cable is connected after bootup
    grep -Fq -- "i.MX6 Ultralite" /proc/cpuinfo || return 0

    # loop forever
    while :; do
        sleep 20
        ip -o addr show  eth0 | grep -Fq -- 'inet'       || continue
        ip -o link show  eth0 | grep -Fq -- 'state DOWN' || continue
        tx6ul_eth0_needFix || continue
        echo "trying to set up eth0"
        # FIX
        ip link set down eth0 ; sleep 1
        ip link set up   eth0 ; sleep 3
        # Check result
        ip -o link show  eth0 | grep -Fq -- 'state UP' && echo "eth0 came up"
    done & # background
}

case "$1" in
    start)
        start
        ;;
    stop)
        :
        ;;
    *)
        echo "Usage: $0 {start|stop}"
        exit 1
esac
