#! /usr/bin/env python

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

[wormhole_*]
env.usagedb /path/to/your/wormhole/server/usage.sqlite
"""

from __future__ import print_function
import os, sys, time, sqlite3

CONFIG = """\
graph_title Magic-Wormhole Transit Usage (since reboot)
graph_vlabel Bytes Since Reboot
graph_category wormhole
bytes.label Transit Bytes (complete)
bytes.draw LINE1
bytes.type GAUGE
incomplete.label Transit Bytes (incomplete)
incomplete.draw LINE1
incomplete.type GAUGE
"""

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

dbfile = os.environ["usagedb"]
assert os.path.exists(dbfile)
db = sqlite3.connect(dbfile)

MINUTE = 60.0
updated,rebooted,incomplete = db.execute("SELECT `updated`,`rebooted`,`incomplete_bytes` FROM `current`").fetchone()
if time.time() > updated + 5*MINUTE:
    sys.exit(1) # expired

complete = db.execute("SELECT SUM(`total_bytes`) FROM `usage`"
                      " WHERE `started` > ?",
                      (rebooted,)).fetchone()[0] or 0
print("bytes.value", complete)
print("incomplete.value", complete+incomplete)