mode: 0755
overwrite: true
path: "/usr/local/bin/configure-switchdev.sh"
contents:
  inline: |
    #!/bin/bash
    set -eux
    input="/etc/switchdev.conf"
    UDEV_RULE_FILE='/etc/udev/rules.d/10-persistent-net.rules'

    if [ ! -f $input ]; then
      echo "File /etc/switchdev.conf not exist."
      exit
    fi

    append_to_file(){
      content="$1"
      file_name="$2"
      if ! test -f "$file_name"
      then
        echo "$content" > "$file_name"
      else
        if ! grep -Fxq "$content" "$file_name"
        then
          echo "$content" >> "$file_name"
        fi
      fi
    }

    add_udev_rule_for_sriov_pf(){
        pf_pci=$(grep PCI_SLOT_NAME /sys/class/net/$1/device/uevent | cut -d'=' -f2)
        udev_data_line="SUBSYSTEM==\"net\", ACTION==\"add\", DRIVERS==\"?*\", KERNELS==\"$pf_pci\", NAME=\"$1\""
        append_to_file "$udev_data_line" "$UDEV_RULE_FILE"
    }

    names=()

    while read pci_addr num_vfs
    do
      echo "Set $num_vfs VFs on device $pci_addr"

      name=$(ls /sys/bus/pci/devices/${pci_addr}/net/)
      names+=($name)
      # Create udev rule to save PF name
      add_udev_rule_for_sriov_pf $name

      # create VFs
      echo $num_vfs > /sys/bus/pci/devices/${pci_addr}/sriov_numvfs
    done <"$input"

    # wait for vfs to be ready
    sleep 5
    i=0
    while read pci_addr num_vfs
    do
      # unload VF driver
      VfDirs=$(ls /sys/bus/pci/devices/${pci_addr} | grep virtfn)
      for VfDir in $VfDirs
      do
        VfPciAddr=$(basename "$( readlink -f /sys/bus/pci/devices/${pci_addr}/$VfDir )")
        echo $VfPciAddr > /sys/bus/pci/drivers/mlx5_core/unbind || true

      done

      # set PF to switchdev mode
      devlink dev eswitch set pci/${pci_addr} mode switchdev

      ip link set ${names[i]} up

      # turn hw-tc-offload on
      /usr/sbin/ethtool -K ${names[i]} hw-tc-offload on

      i=$(( i+1 ))

      # load VF driver
      for VfDir in $VfDirs
      do
        VfPciAddr=$(basename "$( readlink -f /sys/bus/pci/devices/${pci_addr}/$VfDir )")
        echo $VfPciAddr > /sys/bus/pci/drivers_probe
      done
    done <"$input"
