#!/bin/bash

# Initial Author: D.Bienz
# This script ensures that the QCA interfaces are named properly. After initialization, the are named ethX.
# We want to address them by qca0 to qca3. This scripts checks the ethernet interfaces from index $FIRST_QCA_INDEX to
# index $MAX_QCA_NUMBERS. The qca MAC address at startup is defined with $BASE_MAC and index of the QCA. Therefore,
# the ethernet interface ethX can be renamed to the affected qcaX by looking at the last digit of the MAC address (x).

BASE_MAC="a0:b0:c0:d0:e0:f" # The initial MAC address of the QCA IC is configured in the Device Tree!
BASE_QCA_IFACE_NAME="qca"
BASE_ETH_IFACE_NAME="eth"
FIRST_QCA_INDEX=1
MAX_QCA_NUMBERS=4
ETHERNET_DEVICE_PATH_BASE="/sys/class/net/eth"
ETHERNET_DEVICE_PATH_END="/address"


# Function to rename an IP interface in Linux (using iproute2)
rename_ip_interface () {
  #$1 is current name (e.g. eth1)
  #$2 is new name (e.g. qca0)
  ip link set $1 down
  ip link set $1 name $2
  ip link set $2 up
  echo "Renamed $1 to $2."
}

for i in $(seq $FIRST_QCA_INDEX $MAX_QCA_NUMBERS); do
  path=$ETHERNET_DEVICE_PATH_BASE$i$ETHERNET_DEVICE_PATH_END
  if [ -f "$path" ]; then
    if grep -q $BASE_MAC"0" "$path"; then
      rename_ip_interface $BASE_ETH_IFACE_NAME$i $BASE_QCA_IFACE_NAME"0"
    elif grep -q $BASE_MAC"1" "$path"; then
      rename_ip_interface $BASE_ETH_IFACE_NAME$i $BASE_QCA_IFACE_NAME"1"
    elif grep -q $BASE_MAC"2" "$path"; then
      rename_ip_interface $BASE_ETH_IFACE_NAME$i $BASE_QCA_IFACE_NAME"2"
    elif grep -q $BASE_MAC"3" "$path"; then
      rename_ip_interface $BASE_ETH_IFACE_NAME$i $BASE_QCA_IFACE_NAME"3"
    fi
  else
    echo "No device at $path"
  fi
done