#!/bin/sh
# Detect Ethernet port ARP failures
# Requires CTM-200 FW with mii-diag
# Cypress Solutions Inc (C) 2014

MAX_FAIL=5
DELAY=30
ETHFAIL_DELAY=5

check_eth()
{
	count_eth=0
	while [ $count_eth -lt $MAX_FAIL ]; do
		if [ $1 == "eth0" ] ;then
			eth_phy=$(mii-diag $1 2> /dev/null | grep "PHY #6" | awk '{print $8}' | awk '{print substr($0,4,1)}')
		fi
		if [ $1 == "eth1" ] ;then
			eth_phy=$(mii-diag $1 2> /dev/null | grep "PHY #7" | awk '{print $8}' | awk '{print substr($0,4,1)}')
		fi
		
		#logger "arpdetect: check_eth: $1 $eth_phy"
		
		if [ $eth_phy == "d" ] ;then
			ip_addr_eth=$(ip addr show $1 | grep "state DOWN" | wc -l)
			if [ $ip_addr_eth -eq 1 ] ;then				
				count_eth=$((count_eth+1))
				#logger "arpdetect_$1_FAIL: $count_eth"
				if [ $count_eth -eq $MAX_FAIL ] ;then
					#logger "arpdetect_$1_REBOOT"
					cmd event add "arpdetect_$1_REBOOT"
					cmd pwr mode 2
				fi
				sleep $ETHFAIL_DELAY
			fi
			if [ $ip_addr_eth -eq 0 ] ;then
				count_eth=0
				break
			fi
		fi
		if [ $eth_phy != "d" ] ;then
				count_eth=0
				break
		fi
	done
}

while :
do
	check_eth eth0
	check_eth eth1
	sleep $DELAY
done
