#!/bin/bash

set -e

# Get the default route
default_route=$(ip route | grep default)

# Extract the NIC interface name
nic=$(echo $default_route | awk '{print $5}')

# Get current link speed of interface
link_speed=$(ethtool $nic 2>/dev/null | grep "Speed:" | awk '{print $2}')

# Get the PCI ID for the NIC interface
pci_id=$(ethtool -i $nic 2>/dev/null | grep bus-info | awk '{print $2}')

# Extract speed and unit
speed_value=$(echo $link_speed | sed 's/[A-Za-z\/]*//g')
speed_unit=$(echo $link_speed | sed 's/[0-9]*//g')

# Convert speed to a human-readable format
case $speed_unit in
  "Mb/s")
    if [ $speed_value -ge 1000 ]; then
      speed_value=$(bc <<< "scale=1; $speed_value/1000")
      speed_unit="Gb/s"
    fi
    ;;
  "Gb/s")
    # If you need to handle more units, you can extend here
    ;;
  *)
    #echo "Unknown speed unit: $speed_unit"
    speed_value=""
    speed_unit=""
    ;;
esac

# Check if PCI ID is found
if [ -z "$pci_id" ]; then
    #echo "PCI ID not found for interface: $nic"
    exit 1
else
    # Get the human-readable name of the device
    device_name=$(lspci -s $pci_id | cut -d ' ' -f 4-)
fi

# Hee Hoo jank :)
if [[ ! -z $speed_value && ! -z $speed_unit ]]; then
    speed_value="[${speed_value}"
    speed_unit="${speed_unit}]"
else
    speed_value=""
    speed_unit=""
fi

echo "$device_name" "${speed_value} ${speed_unit}"

