#! /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
from collections import defaultdict

CONFIG = """\
graph_title Magic-Wormhole Server Events
graph_vlabel Events per Hour
graph_category wormhole
happy.label Happy
happy.draw LINE
happy.type DERIVE
happy.min 0
happy.max 60
happy.cdef happy,3600,*
incomplete.label Incomplete
incomplete.draw LINE
incomplete.type DERIVE
incomplete.min 0
incomplete.max 60
incomplete.cdef incomplete,3600,*
scary.label Scary
scary.draw LINE
scary.type DERIVE
scary.min 0
scary.max 60
scary.cdef scary,3600,*
"""

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

usagedbfile = os.environ["usagedb"]
assert os.path.exists(usagedbfile)
usage_db = sqlite3.connect(usagedbfile)

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

atm = defaultdict(int)
for mood in ["happy", "scary", "lonely", "errory", "pruney", "crowded"]:
    atm[mood] = usage_db.execute("SELECT COUNT() FROM `mailboxes`"
                                 " WHERE `result` = ?", (mood,)).fetchone()[0]

print("happy.value", atm["happy"])
print("incomplete.value", (atm["pruney"] + atm["lonely"]))
print("scary.value", atm["scary"])
