#!/bin/bash

INTERFACE=$(ip route get 8.8.8.8 2>/dev/null | awk '{print $5; exit}')
[ -z "$INTERFACE" ] && INTERFACE="eth0"

RX_PATH="/sys/class/net/$INTERFACE/statistics/rx_bytes"
TX_PATH="/sys/class/net/$INTERFACE/statistics/tx_bytes"

OUTFILE="/tmp/waybar_net_speed_output"

prev_rx=$(cat "$RX_PATH")
prev_tx=$(cat "$TX_PATH")
prev_time=$(date +%s)

while true; do
  sleep 1

  cur_rx=$(cat "$RX_PATH")
  cur_tx=$(cat "$TX_PATH")
  cur_time=$(date +%s)

  drx=$((cur_rx - prev_rx))
  dtx=$((cur_tx - prev_tx))
  dt=$((cur_time - prev_time))

  if (( dt > 0 )); then
    rx_mbps=$(awk "BEGIN { printf \"%.1f\", $drx * 8 / 1024 / 1024 / $dt }")
    tx_mbps=$(awk "BEGIN { printf \"%.1f\", $dtx * 8 / 1024 / 1024 / $dt }")
    echo " ${rx_mbps}Mbit/s   ${tx_mbps}Mbit/s" > "$OUTFILE"
  fi

  prev_rx=$cur_rx
  prev_tx=$cur_tx
  prev_time=$cur_time
done
