#! /usr/bin/env python

"""
Use the following in /etc/munin/plugin-conf.d/wormhole :

[wormhole_*]
env.serverdir /path/to/your/wormhole/server
"""

import os, sys, time, json

def count_events():
    serverdir = os.environ["serverdir"]
    dbfile = os.path.join(serverdir, "relay.sqlite")
    if not os.path.exists(dbfile):
        print "cannot find relay.sqlite, please set env.serverdir"
        sys.exit(1)
    db = sqlite3.connect(dbfile)

    c_list = []
    c_dict = {}
    def add(key, value):
        c_list.append((key, value))
        c_dict[key] = value
    def q(query, values=()):
        return db.execute(query, values).fetchone()[0]

    add("apps", q("SELECT COUNT(DISTINCT(`app_id`)) FROM `nameplate_usage`"))

    add("total nameplates", q("SELECT COUNT() FROM `nameplate_usage`"))
    add("happy nameplates", q("SELECT COUNT() FROM `nameplate_usage`"
                              " WHERE `result`='happy'"))
    add("lonely nameplates", q("SELECT COUNT() FROM `nameplate_usage`"
                               " WHERE `result`='lonely'"))
    add("pruney nameplates", q("SELECT COUNT() FROM `nameplate_usage`"
                               " WHERE `result`='pruney'"))
    add("crowded nameplates", q("SELECT COUNT() FROM `nameplate_usage`"
                                " WHERE `result`='crowded'"))

    add("total mailboxes", q("SELECT COUNT() FROM `mailbox_usage`"))
    add("happy mailboxes", q("SELECT COUNT() FROM `mailbox_usage`"
                             " WHERE `result`='happy'"))
    add("scary mailboxes", q("SELECT COUNT() FROM `mailbox_usage`"
                             " WHERE `result`='scary'"))
    add("lonely mailboxes", q("SELECT COUNT() FROM `mailbox_usage`"
                              " WHERE `result`='lonely'"))
    add("errory mailboxes", q("SELECT COUNT() FROM `mailbox_usage`"
                              " WHERE `result`='errory'"))
    add("pruney mailboxes", q("SELECT COUNT() FROM `mailbox_usage`"
                              " WHERE `result`='pruney'"))
    add("crowded mailboxes", q("SELECT COUNT() FROM `mailbox_usage`"
                               " WHERE `result`='crowded'"))

    add("total transit", q("SELECT COUNT() FROM `transit_usage`"))
    add("happy transit", q("SELECT COUNT() FROM `transit_usage`"
                           " WHERE `result`='happy'"))
    add("lonely transit", q("SELECT COUNT() FROM `transit_usage`"
                            " WHERE `result`='lonely'"))
    add("errory transit", q("SELECT COUNT() FROM `transit_usage`"
                            " WHERE `result`='errory'"))

    add("transit bytes", q("SELECT SUM(`total_bytes`) FROM `transit_usage`"))

    return c_dict

CONFIG = """\
graph_title Magic-Wormhole Transit Usage
graph_vlabel Bytes Since Reboot
graph_category network
bytes.label Transit Bytes
bytes.draw LINE1
bytes.type GAUGE
"""

if len(sys.argv) > 1 and sys.argv[1] == "config":
    print CONFIG.rstrip()
    sys.exit(0)

serverdir = os.environ["serverdir"]
fn = os.path.join(serverdir, "stats.json")
with open(fn) as f:
    data = json.load(f)
if time.time() > data["valid_until"]:
    sys.exit(1) # expired

t = data["transit"]["since_reboot"]
print "bytes.value", t["bytes"]