#!/bin/bash

# This file renames netdevice of the SF's auxiliary device.
# It is done by using its parent PCI device + sf number.
#
# For example, when SF with sfnumber 88 is located on its parent PCI Device 03:00.0, it will be named renamed as,
#
# enp3s0f0s88.
#
# en = Ethernet
# p = pci
# 3s0sf0 = pci bdf = 0x3:00.0
# s88 = SF number 88

SFNUM=$1
IFINDEX=$2

# Names for the first 4 SFs on ECPF0  (function 0)
declare -A P0_SFMAP=( [0]="p0_sf" [1]="pf0hpf_sf" [2]="pf0dpu0_sf" [3]="pf0dpu1_sf" )

# SF numbers 4 to 127 on ECPF0 (function 0) are mapped to VFs and follow pattern pf0vfx_sf
for i in $(seq 4 127);  do
	vf_idx=$((${i}-4))
	P0_SFMAP[$i]="pf0vf${vf_idx}_sf"
done

# Names for the first 2 SFs on ECPF1  (function 1)
declare -A P1_SFMAP=( [0]="p1_sf" [1]="pf1hpf_sf" )
# SF numbers 2 to 127 on ECPF1 (function 1) are mapped to VFs and follow pattern pf1vfx_sf
for i in $(seq 2 127);  do
	vf_idx=$((${i}-2))
	P1_SFMAP[$i]="pf1vf${vf_idx}_sf"
done


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
		_sfnum=`cat /sys/class/net/$sf_ndev/device/sfnum | head -1 2>/dev/null`
		if [ "$_sfnum" = "$SFNUM" ]
		then
			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}


			if (( $f == 0 )); then
				sf_name="${P0_SFMAP[${SFNUM}]}"
			elif (( $f == 1 )) ; then
				sf_name="${P1_SFMAP[${SFNUM}]}"
			else
				echo "Cannot rename device. Function: $f : expected to either 0 or 1 " > /dev/kmsg
			fi

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