#!/bin/bash

i=$1
ifindex=$2

# need the PATH for BF ARM lspci to work
PATH=/opt/mellanox/iproute2/sbin:/opt/mellanox/ethtool/sbin:/bin:/sbin:/usr/bin:/usr/sbin
SUPPORTED_DEVICES="a2d[26cf]|1023|1025"

is_bf=`lspci -s 00:00.0 2> /dev/null | grep -wq "PCI bridge: Mellanox Technologies" && echo 1 || echo 0`
if [ $is_bf -ne 1 ]; then
	# Check if the device is a Mellanox BlueField 4 or newer
	if [ -e /etc/mlnx-release ]; then
		if [ $(lspci -nD -d 15b3: | grep -E "$SUPPORTED_DEVICES" | wc -l) -eq 0 ]; then
			exit 0
		fi
	else
		exit 0
	fi
fi

get_interface_by_index()
{
	ifindex=$1
	for ipath in $(/bin/ls -1d /sys/class/net/*)
	do
		if [ "$(cat ${ipath}/ifindex 2> /dev/null)" == "$ifindex" ]; then
			echo $(basename $ipath)
			return
		fi
	done
}

if [ -n "$ifindex" ]; then
	i=$(get_interface_by_index $ifindex)
fi

if [ ! -n "$i" ] || [ ! -d /sys/class/net/$i ]; then
	exit 0
fi

# Set combined channels: 4 for uplink PFs and ASTRA ports, 2 for others
case "$i" in
	p[0-9]|p[0-9][0-9]|A*|B*)
	ethtool -L $i combined 4
	;;
	*)
	ethtool -L $i combined 2
	;;
esac

# Bring up only renamed devices
case "$i" in
	eth*)
	;;
	*)
	ip link set dev $i up
	;;
esac
