#!/usr/bin/env python

# Version 0.1 alpha (a.k.a. it has been known to work at least once)
# Get stats from your i2p server ( https://geti2p.net/en/ )
# Create links to this plugin and name them
# - i2p_bps
# - i2p_uptime (not implemented yet)
# Requires BeautifulSoup 4

# Should probably use I2PControl for this instead
# https://geti2p.net/en/docs/api/i2pcontrol

import urllib2, re, os, sys
from bs4 import BeautifulSoup
from decimal import *

plugin_name=list(os.path.split(sys.argv[0]))[1]
plugin_var=plugin_name.split('_', 1)[-1]

def autoconf():
  print('yes')
  sys.exit(0)

def config():
  if 'bps' == plugin_var:
    print('graph_title i2p bps')
    print('graph_vlabel bps')
    print('graph_info i2p sending and receiving bytes per second')
    print('graph_category i2p')
    print('receivebps.label Receive bps')
    print('sendbps.label Send bps')
  elif 'uptime' == plugin_var:
    print('graph_title i2p uptime')
    print('graph_scale no')
    print('graph_args --base 1000 -l 0')
    print('graph_vlabel uptime in whole hours')
    print('graph_category i2p')
    print('uptime.label i2p uptime')
    print('uptime.draw AREA')
  else:
    raise ValueError, "unknown parameter '%s'" % plugin_var
  sys.exit(0)

def fetch():
  html_doc = urllib2.urlopen('http://127.0.0.1:7657/stats').read()
  soup = BeautifulSoup(html_doc)
  if 'bps' == plugin_var:
    fetch_bps(soup)
  elif 'uptime' == plugin_var:
    fetch_uptime(soup)
  else:
    raise ValueError, "unknown parameter '%s'" % plugin_var

def fetch_bps(soup):
  anchor_bwreceiveBps = soup.find('a', attrs={"name": "bw.receiveBps"})
  b_5min_bwreceiveBps = anchor_bwreceiveBps.find_all_next('b', limit=2)[1]
  bwreceiveBps = Decimal(re.search('Average: ([0-9,\.]+?);', b_5min_bwreceiveBps.parent.get_text()).group(1).replace(',', ''))
  anchor_bwsendBps = soup.find('a', attrs={"name": "bw.sendBps"})
  b_5min_bwsendBps = anchor_bwsendBps.find_all_next('b', limit=2)[1]
  bwsendBps = Decimal(re.search('Average: ([0-9,\.]+?);', b_5min_bwsendBps.parent.get_text()).group(1).replace(',', ''))
  print('receivebps.value %s' % bwreceiveBps)
  print('sendbps.value %s' % bwsendBps)
  sys.exit(0)

def fetch_uptime(soup):
  # not implemented yet
  print('uptime.value U')
  sys.exit(0)

if __name__ == '__main__':
  if len(sys.argv)>1 :
    if sys.argv[1]=="config" :
      config()
    elif sys.argv[1]=="autoconf" :
      autoconf()
    elif sys.argv[1]!="":
      raise ValueError, "unknown parameter '%s'" % sys.argv[1]
  fetch()
