#!/bin/bash

# ********************************************************************************
# QLogic script file for Upgrading firmware.
# ********************************************************************************

# ********************************************************************************
# Update the file names when required.
# Firmware files listed below MUST be at the same folder level as the script file,
# when running this script
# ********************************************************************************

export  SUCCESS=95
export  MBI=.bin
export  FWUTIL=lnxfwnx2
export  PKG=lnxfwnx2-*.sdk.tgz
export  QL_ENABLE_PLDM=1

# --------------------------------------------
#    Set Global Options
# --------------------------------------------
shopt -s nocasematch
RED='\033[0;31m'
BLUE='\033[01;34m'
NC='\033[0m' # No Color

print_err(){
echo -e ${RED}$1 ${NC}
}

print_msg(){
echo -e ${BLUE}$1 ${NC}
}

CheckFileExist() {
if [ `ls | grep -i -c $1` -eq '0' ]; then
  print_err "Error: $1 is missing"
  return 1
fi

  return 0
}

# ******************
# Check for tar package.
# ******************
CheckFileExist $PKG
if [ "$?" -eq "1" ]; then
  exit 1
fi

# ******************
# Extract TGZ (if exists)
# ******************
if [ -f ./$PKG ]; then
  print_msg "Extracting package contents..."
  tar -xzf $PKG
fi

# ******************
# Check for Firmware Upgrade Utility.
# ******************
CheckFileExist $FWUTIL
if [ "$?" -eq "1" ]; then
  exit 1
fi

# ******************
# Upgrade MBI.
# ******************
CheckFileExist $MBI
if [ "$?" -eq "0" ]; then
MBI_FILES=$(ls | grep -i $MBI)
for MBI_FILE in $MBI_FILES
do
./$FWUTIL -all upgrade -f -mbi  $MBI_FILE
RET_FLASH=$?
if [ $RET_FLASH = $SUCCESS ] ; then
    print_msg "Successfully upgraded $MBI_FILE"
else
    print_err "Failed to upgraded MBI"
	exit $RET_FLASH
fi
done
else 
	exit 1
fi

exit $SUCCESS 

