#!/bin/sh

# This is run by systemd from the sx_sdk unit file.

# On some cases we don't want to stop SDK after a failed upgrade
skip_upgrade_status_check=

while [ "$1" != "" ]; do
  case $1 in
    "-s" | "--skip_upgrade_status_check")
      skip_upgrade_status_check=true
      ;;
  esac
  shift
done


# check and update firmware if needed
if /usr/bin/platform-detect | grep -q 'msn4800'; then
	rm -rf /dev/mst/mt6518_pciconf*
fi

# On Palladium we do not want to run mlxfwupgrade.sx
if /usr/bin/platform-detect | grep -q 'pld_sn5600'; then
        echo "mlxfwupgrade.sx skipped!"
elif /usr/bin/platform-detect | grep -q 'simx'; then
        echo "SimX platform detected: skipping mlxfwupgrade.sx"
elif [ -f "/home/cumulus/skip_fw_update" ]; then
    echo "mlxfwupgrade.sx skipped due to presence of /home/cumulus/skip_fw_update file!"
else
  /usr/lib/cumulus/mlxfwupgrade.sx
	retVal=$?
  if [ $retVal -ne 0 ]; then
      if [ -z "$skip_upgrade_status_check" ]; then
        echo "mlxfwupgrade failed skipping sx_sdk start"
        systemctl stop sx_sdk
      else
        echo "mlxfwupgrade failed"
      fi
      exit $retVal
  fi
	sleep 10
fi

#Drivers are always reloaded to force firmware reset
cd /usr/lib/cumulus/ && \
PATH="$PATH:/usr/lib/cumulus/" /usr/lib/cumulus/sxdkernel start

exec /usr/bin/sx_sdk --syslog
