#!/usr/bin/env python3
# backend of my workaround to get network usage in i3bar

from pathlib import Path
from time import time, sleep
import os

SYS_FOLDER = Path("/sys/class/net")
SHM_FILE = Path('/dev/shm/netusage')
last_item = dict()

# UNITS = ['B/s', 'KB/s', 'MB/s', 'GB/s']
UNITS = ['B', 'K', 'M', 'G']

def normalize_unit(val):
    val = float(val)
    unit_idx = 0
    while val > 100:
        unit_idx += 1
        val = val / 1024
    return f"{val:.1f}{UNITS[unit_idx]}"

def handle_iteration(iface):
    try:
        stats_dir = SYS_FOLDER / iface / "statistics"
        rx = int((stats_dir / "rx_bytes").read_text().strip())
        tx = int((stats_dir / "tx_bytes").read_text().strip())
        timestamp = time()
        if last_item.get(iface) is None:
            last_item[iface]=dict(timestamp=int(timestamp),rx=rx,tx=tx)
            return ""
        prev = last_item[iface]
        time_delta = timestamp - prev['timestamp']
        rx_speed = (rx - prev['rx']) // time_delta
        tx_speed = (tx - prev['tx']) // time_delta
        last_item[iface]=dict(timestamp=timestamp,rx=rx,tx=tx)
        if (rx_speed + tx_speed) > 0:
            return f"{iface} {normalize_unit(rx_speed)} {normalize_unit(tx_speed)} "
        return ""
    except Exception as e:
        print(e)
        return ""


while True:
    strs = map(handle_iteration,  os.listdir(str(SYS_FOLDER)))
    SHM_FILE.write_text("".join(strs))
    sleep(1.0)
