#!/usr/bin/env bash

COUNTER_FILE=/dev/shm/polybar_network_usage
REFRESH=2

get_icon_by_device()
{
    device=$1

    device_type=$(nmcli -t device status | grep -E -m 1 "^$device" | cut -f 2 -d ":")

    case "$device_type" in
        ethernet)
            icon=""
        ;;
        wifi)
            ssid=$(nmcli -t device status | grep -E -m 1 "^$device" | cut -f 4 -d ":")
            icon=" $ssid"
        ;;
        *)
            icon=""
        ;;
    esac

    echo $icon
}

while true; do
    default_device=$(ip route list | grep -Fm 1 default | cut -d " " -f 5)
    icon=$(get_icon_by_device "$default_device")
    now=$(date +%s)
    counter_age=$(stat --format %Z $COUNTER_FILE 2>/dev/null)

    if [ "$default_device" = "link" ]; then
        default_device=$(ip route list | grep -Fm 1 default | cut -d " " -f 3)
    fi

    if [ -f $COUNTER_FILE ] && [ $((now-counter_age)) -lt $((REFRESH+1)) ]; then
        last_value_in=$(cut -f 1 -d " " $COUNTER_FILE)
        last_value_out=$(cut -f 2 -d " " $COUNTER_FILE)
    fi

    current_values=$(awk -v dev="${default_device}:" '{
        if ($1 == dev) print $2,$10
    }' < /proc/net/dev)

    current_bytes_in=$(echo "$current_values" | cut -f 1 -d " ")
    current_bytes_out=$(echo "$current_values" | cut -f 2 -d " ")

    if [ -n "$last_value_in" ]; then
        bits_in=$((((current_bytes_in-last_value_in) / REFRESH) * 8))
        bits_out=$((((current_bytes_out-last_value_out) / REFRESH) * 8))

        output=$(LANG=C numfmt --to iec --format "%8.2f" "$bits_in" "$bits_out" \
                 | tr -d "\n" 2>/dev/null)

        if ! echo "$output" | grep -qE '[0-9]{1,3}\.[0-9]{1,3}([K,M,G,B])?$'; then
            output="  0.01  0.01"
        fi

        echo "$icon $output"
    else
        echo "$icon --  --"
    fi

    echo "$current_values">$COUNTER_FILE
    unset last_value

    sleep $REFRESH
done