#! /usr/bin/env python

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

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

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

CONFIG = """\
graph_title Magic-Wormhole Active Channels
graph_vlabel Channels
graph_category wormhole
nameplates.label Nameplates
nameplates.draw LINE2
nameplates.type GAUGE
mailboxes.label Mailboxes
mailboxes.draw LINE2
mailboxes.type GAUGE
messages.label Messages
messages.draw LINE1
messages.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)

channeldbfile = os.environ["channeldb"]
assert os.path.exists(channeldbfile)
channel_db = sqlite3.connect(channeldbfile)

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

nameplates = channel_db.execute("SELECT COUNT() FROM `nameplates`").fetchone()[0]
mailboxes = channel_db.execute("SELECT COUNT() FROM `mailboxes`").fetchone()[0]
messages = channel_db.execute("SELECT COUNT() FROM `messages`").fetchone()[0]

print("nameplates.value", nameplates)
print("mailboxes.value", mailboxes)
print("messages.value", messages)
