#!/usr/bin/env python3

import os
from okerrupdate.utils import kmgt

def get_default_gateway_linux():
    """Read the default gateway interface directly from /proc."""
    with open("/proc/net/route") as fh:
        for line in fh:
            fields = line.strip().split()
            if fields[1] != '00000000' or not int(fields[3], 16) & 2:
                # If not default route or not RTF_GATEWAY, skip it
                continue
            
            return fields[0]

def get_interface_tx_rx(interface):
    interface_signature = interface+':'
    with open('/proc/net/dev') as fh:
        for line in fh:
            fields = line.split()
            if fields[0] != interface_signature:
                # print("SKIP", interface_signature, fields)
                continue
            return (int(fields[1]), int(fields[9]))
    return (-1, -1)

# read parameters
prefix = os.getenv('PREFIX')
basename = os.getenv('BASENAME')
interfaces = os.getenv('INTERFACES')

for iface_spec in filter(None, interfaces.split(' ')):
    if iface_spec == 'defgw':
        iface = get_default_gateway_linux()
    else:
        iface = iface_spec

    txrx = get_interface_tx_rx(iface)

    for direction, amount in zip(['tx', 'rx'], txrx):
        print("NAME: {}{}-{}".format(prefix, iface_spec, direction))
        print("TAGS: traffic")
        print("DETAILS: {}".format(kmgt(amount)))
        print("METHOD: numerical|minlim=0")
        print("STATUS: {}".format(amount))
        print()
