#! /bin/sh
# check input argument
if [ -z "$1" ];  then
    echo "AQC-AUTOFWUP: Error! No argument supplied!"
    exit
fi

# check FW file exist
echo "$1"
if [ ! -e "$1" ]; then
    echo "AQC-AUTOFWUP: Error! Cannot find FW files!"
    exit
fi

if [ -e "/tmp/ETH_FW_flash_undone" ]; then 
  echo "AQC-AUTOFWUP: Continue to complete interrupted updates."
else
  #AQC112
  #Vendor ID = 0x1D6A
  #Device ID = 0x11B1
  # lspci 01:00.0 Class 0200: 1d6a:11b1
  echo "AQC-AUTOFWUP: probe with vendorid"
  hw_aqc_vid=`lspci | grep 1d6a | awk '{print $4}' | cut -d: -f1`
  hw_aqc_pid=`lspci | grep 1d6a | awk '{print $4}' | cut -d: -f1`
  
  if [ "$hw_aqc_vid" = "1d6a" ]; then
      echo "AQC-AUTOFWUP: found AQC112."
  else
      echo "AQC-AUTOFWUP: NOT found AQC112."
      exit
  fi

  echo "AQC-AUTOFWUP: Check chip is workable or not."
  
  echo "AQC-AUTOFWUP: Compare FW version between fw and fw file."
  chipfw_ver_major=`readstat | grep "Firmware Version =" | head -1 | awk '{print $4}' |  cut -d. -f1`
  chipfw_ver_sub=`readstat | grep "Firmware Version =" | head -1 | awk '{print $4}' |  cut -d. -f2`
  chipfw_ver_minor=`readstat | grep "Firmware Version =" | head -1 | awk '{print $4}' |  cut -d. -f3`
  filefw_ver_major=`ls $1 | grep aqc* | cut -d- -f2 | cut -d. -f 1`
  filefw_ver_sub=`ls $1 | grep aqc* | cut -d- -f2 | cut -d. -f 2`
  filefw_ver_minor=`ls $1 | grep aqc* | cut -d- -f2 | cut -d. -f 3`
  
  echo "AQC-AUTOFWUP: Check Is need to upgrade fw."
  compared_major=`expr $filefw_ver_major - $chipfw_ver_major`
  compared_sub=`expr $filefw_ver_sub - $chipfw_ver_sub`
  compared_minor=`expr $filefw_ver_minor - $chipfw_ver_minor`

  update=0
  if [ $compared_major -gt 0 ]; then
          update=1
  fi
  if [ $compared_sub -gt 0 ]; then
          update=1
  fi
  if [ $compared_minor -gt 0 ]; then
          update=1
  fi 

  if [ $update -eq 1 ]; then
    echo "AQC-AUTOFWUP: FW update."
  else
    echo "AQC-AUTOFWUP: No FW update needed."
    exit
  fi

  touch /data/ETH_FW_flash_undone
  sync
fi

#Get original mac before Update FW
old_mac=`readstat | grep "MAC address =" | awk '{print $4}'`
echo "Ethernet old MAC = $old_mac"

echo Update FW using flashUpdate
flashUpdate -d 01:00.0 $1  --bdp

if [ $? -ne 0 ]; then
	echo flashUpdate fail, using flashBurn instead...
	flashBurn -d 01:00.0 $1
	echo Write back MAC setting...
	flashOverride -d 01:00.0 -m $old_mac
fi

rm /tmp/ETH_FW_flash_undone
sync
