#!/bin/sh

# Script to workaround an issue with AutoIP on the Gira G1.
# If an IP in the range of 169.254.x.x is recognized this script tries to retrieve
# a DHCP address by calling /etc/init.d/ethernet.sh reenable.
# If no DHCP address was assigned after the third try ... go for it.
# Expected to be deprecated on hardware known as DV5 or greater.
# So if your /var/log/message tells you something like
# mmcblk0: mmc0:0001 SEM04G 3.68 GiB
# you have a SanDisk eMMC and thus DV5 or greater.
# If you see H4G1d instead of SEM04G you have DV4 or below.

me="[hasAutoIP]"

getip()
{
  local ipaddr=""
  local counter=0
  local max_tries=30
  while [ "$ipaddr" = "" ]
  do
    sleep 2
    ipaddr="`ifconfig eth0 | grep inet | tr -s " " | cut -d " " -f 3 | cut -b 6-`"
    counter=$((counter+1))
    logger -s "${me} getip (${counter}): |${ipaddr}|"
    if [ ${counter} -eq ${max_tries} ]
    then
      break;
    fi
  done
  printf "%s\\n" "$ipaddr"
}

RX_ERRORS=$(ifconfig eth0 | grep "RX packets" | tr -s " " | cut -d " " -f 4 | cut -d ":" -f 2)
TX_ERRORS=$(ifconfig eth0 | grep "TX packets" | tr -s " " | cut -d " " -f 4 | cut -d ":" -f 2)

counter=1
while [ $(ifconfig eth0 | grep inet | wc -l) -eq 0 ]
do
  logger -s "${me} No IP until now. Waiting ${counter} of 60..."
  sleep 1
  counter=$((counter+1))
  [ $counter -lt 61 ] || break
done

AUTO_IP=$(ifconfig eth0 | grep "169.254" | wc -l)

if [ ${AUTO_IP} -gt 0 ]
then
  logger -s "${me} AutoIP received: ${ipaddr}. Trying workaround."
  if [ ${RX_ERRORS} -gt 0 ] || [ ${TX_ERRORS} -gt 0 ]
  then
    logger -s "${me} RX errors: ${RX_ERRORS} and TX errors: ${TX_ERRORS}"
  else
    logger -s "${me} There are no errors on RX and TX. So this seems to be OK."
  fi
  
  while [ ! "$counter" = "3" ]
  do
    counter=$((counter+1))
    logger -s "${me} Reenabling ethernet device. Try (${counter})"
    /etc/init.d/ethernet.sh reenable
    sleep 2
    # Reenabling the device three times without checking for the IP
    # seems to have the same effect as waiting and checkking ... except it's much faster.
#    ipaddr=`getip`
#    logger -s "${me} IP after reenabling eth0: ${ipaddr}."
#    if ! [ "`printf "%s\\n" "$ipaddr" | cut -b 1-3`" = "169" ]
#    then
#      break;
#    fi
  done
  ipaddr=`getip`
  logger -s "${me} IP after reenabling eth0: ${ipaddr}."
fi

exit 0
