#!/bin/bash -x
#
# 1) edit ETH variable to match target machine
# 2) scp reload_asix root@$IP:/tmp
# 3) set T="root@$IP"
#
# then invoke on a "host" machine (in chroot) with:
# for i in `seq 10000`; do
#	echo -n "RELOAD $i  "
#	ssh $T '. /tmp/reload_asix eth0 100_full'
#	J=$? ; if [ $J -eq 255 ] ; then echo "  SSH timeout" ; break ; fi
#	ssh $T "cat /tmp/reload-asix.out"
#	if [ $J -ne 0 ] ; then echo "  ERROR $J" ; fi
#	sleep 3
# done | tee reload_asix-loop.out

ETH="$1"

DRIVER=$(ethtool -i $ETH | awk '/driver:/ { print $2 }')

# e.g. LINKSP="1000_full" or "100_full"
# "$(cat /sys/class/net/$ETH/speed)_$(cat /sys/class/net/$ETH/duplex)"
# We can't read it here since current state might be wedged from
# previous iteration. Toggling authorized field might fix it.
LINKSP="$2"

# assuming only one ASIX device is plugged in...really want to key off $ETH
AUTH=$(find /sys/devices -name manufacturer | xargs fgrep -l ASIX | sed 's/manufacturer/authorized/')

# redirect all output to a file. SSH might drop.
# exec > /tmp/`date  --rfc-3339=date`-reload-$$.out 2>&1
exec > /var/log/reload-$DRIVER.out 2>&1

echo -n "$(date +"%Y%m%d%H%M%S")"

mac="$(cat /sys/class/net/$ETH/address)"
ip="$(ifconfig $ETH | awk '/inet / { print $2}')"
rmmod $DRIVER

# side effect of auth/deauth is a USB reset on reconnect. :)
echo 0 > $AUTH
sleep 1

modprobe $DRIVER

echo 1 > $AUTH
sleep 1

mac2="$(cat /sys/class/net/$ETH/address)"
if [ "$mac" != "$mac2" ] ; then
	echo "  MAC mismatch before link: $mac != $mac2  reread: $(cat /sys/class/net/$ETH/address)"
	exit 254
fi

let i=0
l="NULL"
while [ "$l" != "$LINKSP" -a  $i -lt 60 ] ; do
	sleep 1
	let i+=1
	l="$(cat /sys/class/net/$ETH/speed)_$(cat /sys/class/net/$ETH/duplex)"
done

printf "  LINK %s (%d sec)" "$l" $i

mac2="$(cat /sys/class/net/$ETH/address)"
if [ "$mac" != "$mac2" ] ; then
	echo
	echo "  MAC mismatch after link: $mac != $mac2  reread: $(cat /sys/class/net/$ETH/address)"
	exit 253
fi

if [ "$l" != "$LINKSP" ] ; then
	exit 252
fi

let i=0
ip2=" "
while [ $i -lt 60 ] ; do
   sleep 1
   let i+=1
   
   ip2="$(ifconfig $ETH | awk '/inet / { print $2}')"
   if [ "$ip" = "$ip2" ] ; then
      printf "  IP %s (%d Sec)\n" $ip $i
      exit 0
   fi
done

exit 251
