#!/usr/bin/env python3

import os
import sys
import time
import signal
import cursor
import curses
from ascii_graph import Pyasciigraph

def rxtxcount(rxpath, txpath):
  rx1 = int(open(rxpath).read().replace('\n',''))
  tx1 = int(open(txpath).read().replace('\n',''))
  time.sleep(1)
  rx2 = int(open(rxpath).read().replace('\n',''))
  tx2 = int(open(txpath).read().replace('\n',''))
  return abs(rx1-rx2)*0.001, abs(tx1-tx2)*0.001, rx2*0.000001, tx2*0.000001

# check if the network device exists and is operating
def checkdevice(sysdir, device):

  if device not in os.listdir(sysdir):
    return False

  if open(sysdir + device + '/operstate').read().replace('\n','') != 'up':
    return False
  return True

# find all network devices that are up
def finddevices(sysdir):
  devices = []
  for i in os.listdir(sysdir):
    if open(sysdir + i + '/operstate').read().replace('\n','') == 'up':
      devices.append(i)
  return devices

def checkos():
  if 'linux' not in sys.platform:
    print('Not a linux machine.')
    sys.exit()

# clean up when sigterm or siginit is sent
def sigterm_handler(signal, frame):
  cursor.show()
  curses.echo()
  curses.nocbreak()
  curses.endwin()
  sys.exit()

signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGINT, sigterm_handler)

def main():

  if (len(sys.argv) > 1) and 'help' in sys.argv[1]:
    print('usage: netmon [network device]'.format(sys.argv[0]))
    sys.exit()

  checkos()

  sysdir = '/sys/class/net/'
  devices = []

  if len(sys.argv) > 1:
    for i in sys.argv:
      if checkdevice(sysdir, i):
        devices.append(i)

  if not devices:
    devices = finddevices(sysdir)

  if not devices:
    print('no appropriate device found')

  # init cursors env
  cursor.hide()
  stdscr = curses.initscr()
  stdscr.clear()
  cursor.hide()
  curses.noecho()
  curses.cbreak()

  # init graph params
  graph = Pyasciigraph(
    line_length=120,
    min_graph_length=50,
    separator_length=2,
    multivalue=True,
    human_readable='si',
    graphsymbol='*',
    float_format='{0:,.2f}',
    force_max_value=100,
  )

  for idx, val in enumerate(devices):
    rxbytepath = sysdir + val + '/statistics/rx_bytes'
    txbytepath = sysdir + val + '/statistics/tx_bytes'
    while True:
      sample = rxtxcount(rxbytepath, txbytepath)
      graphdata = graph.graph('network monitor ({0})'.format(str(val)), [('received (KB/s)', sample[0]), ('sent (KB/s)', sample[1])])
      stdscr.addstr(idx,0,graphdata[0])
      stdscr.addstr(idx+1,0,graphdata[1])
      stdscr.addstr(idx+2,0,graphdata[2])
      stdscr.addstr(idx+3,0,graphdata[3])
      stdscr.addstr(idx+4, 0, "Total received: {0:.2f} MBs".format(sample[2]))
      stdscr.addstr(idx+5, 0, "Total sent: {0:.2f} MBs".format(sample[3]))
      stdscr.refresh()

if __name__ == "__main__":
    main()
