#!/bin/bash
#
# Udev script to rename SF netdevice
# SF netdevices that aren't used by HBN renamed to conventional name, eg. enp3s0f0s88

SFNUM=$1
IFINDEX=$2

source /etc/mellanox/sfc.conf  # Get mappings

for sf_ndev in `ls /sys/class/net/`; do
	_ifindex=`cat /sys/class/net/$sf_ndev/ifindex | head -1 2>/dev/null`
	if [ "$_ifindex" != "$IFINDEX" ]; then continue; fi

	_ifnum=`cat /sys/class/net/$sf_ndev/device/sfnum | head -1 2>/dev/null`
	if [ "$_ifnum" != "$SFNUM" ];then continue; fi

	devpath=`udevadm info /sys/class/net/$sf_ndev | grep "DEVPATH="`
	pcipath=`echo $devpath | awk -F "/mlx5_core.sf" '{print $1}'`
	array=($(echo "$pcipath" | sed 's/\// /g'))
	len=${#array[@]}
	# last element in array is pci parent device
	parent_pdev=${array[$len-1]}
	#pdev is : 0000:03:00.0, so extract them by their index
	b=`echo ${parent_pdev:5:2} | sed 's/^0//'`
	d=`echo ${parent_pdev:8:2} | sed 's/^0//'`
	f=${parent_pdev: -1}

	sf_name="${SF_NAME_BY_SFNUM[${SFNUM}]:-}"

	# non-HBN SF netdevice, use conventional name
	[ -z "$sf_name" ] && sf_name="enp${b}s${d}f${f}s${SFNUM}"

	echo "${sf_name}" >> /tmp/sf_devices
	echo "SF_NETDEV_NAME=${sf_name}"
	exit
done
