#!/bin/bash

INTERFACE=$(ip route | grep default | awk '{print $5}' | head -n1)
STATE_FILE="/tmp/.net_speed_prev_$INTERFACE"

RX_NOW=$(cat /sys/class/net/$INTERFACE/statistics/rx_bytes)
TX_NOW=$(cat /sys/class/net/$INTERFACE/statistics/tx_bytes)
TIME_NOW=$(date +%s)

if [[ ! -f "$STATE_FILE" ]]; then
    echo "$RX_NOW $TX_NOW $TIME_NOW" > "$STATE_FILE"
    echo "0↓ 0↑"
    exit
fi

read RX_PREV TX_PREV TIME_PREV < "$STATE_FILE"
RX_DIFF=$((RX_NOW - RX_PREV))
TX_DIFF=$((TX_NOW - TX_PREV))
TIME_DIFF=$((TIME_NOW - TIME_PREV))
echo "$RX_NOW $TX_NOW $TIME_NOW" > "$STATE_FILE"
(( TIME_DIFF == 0 )) && TIME_DIFF=1

RX_RATE=$((RX_DIFF / TIME_DIFF))
TX_RATE=$((TX_DIFF / TIME_DIFF))

format_speed() {
    local b=$1
    if (( b > 1048576 )); then
        echo "$((b / 1048576))M"
    elif (( b > 1024 )); then
        echo "$((b / 1024))K"
    else
        echo "${b}B"
    fi
}

echo "$(format_speed $RX_RATE)↓ $(format_speed $TX_RATE)↑"
