#! /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 Server Errors
graph_vlabel Events Since Reboot
graph_category wormhole
nameplates.label Nameplate Errors (total)
nameplates.draw LINE1
nameplates.type GAUGE
mailboxes.label Mailboxes (total)
mailboxes.draw LINE1
mailboxes.type GAUGE
mailboxes_scary.label Mailboxes (scary)
mailboxes_scary.draw LINE1
mailboxes_scary.type GAUGE
"""

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

r1 = usage_db.execute("SELECT COUNT() FROM `nameplates` WHERE `started` >= ?",
                      (rebooted,)).fetchone()[0]
r2 = usage_db.execute("SELECT COUNT() FROM `nameplates`"
                      " WHERE `started` >= ?"
                      "  AND `result` = 'happy'",
                      (rebooted,)).fetchone()[0]
print("nameplates.value", (r1 - r2))
r1 = usage_db.execute("SELECT COUNT() FROM `mailboxes` WHERE `started` >= ?",
                      (rebooted,)).fetchone()[0]
r2 = usage_db.execute("SELECT COUNT() FROM `mailboxes` WHERE `started` >= ?"
                      " AND `result` = 'happy'",
                      (rebooted,)).fetchone()[0]
print("mailboxes.value", (r1 - r2))
r = usage_db.execute("SELECT COUNT() FROM `mailboxes` WHERE `started` >= ?"
                     " AND `result` = 'scary'",
                     (rebooted,)).fetchone()[0]
print("mailboxes_scary.value", r)
