#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8
#
# Munin plugin to monitor lighttpd web-server.
#
# Copyright Igor Borodikhin
#
# License : GPLv3
#
# Configuration parameters:
# env.status_url - url of lighty's server-status (optional, default is http://127.0.0.1/server-status)
# env.username - username to provide if status_url requires basic authentication (optional, default - no authentication)
# env.password - password to provide if status_url requires basic authentication (optional, default - no authentication)
#
# Note: If basic HTTP authentication is required you should specify both username and password.
#
# ## Installation
# Copy file to directory /usr/share/munin/plugins/
# Because this plugin has suggest capability the last step is to run
#     # munin-node-configure --suggest --shell | sh -x
#
#%# family=contrib
#%# capabilities=autoconf suggest

import os, sys, urllib2, base64

program = sys.argv[0]
graph_type = program[program.rfind("_")+1:]
graph_types = {
    "accesses" : [
        {
            "title" : "Total accesses",
            "type" : "COUNTER",
            "args" : "--base 1000 -l 0",
            "fields" : ["accesses"]
        }
    ],
    "kbytes" : [
        {
            "title" : "Total kBytes",
            "type" : "COUNTER",
            "args" : "--base 1024 -l 0",
            "fields" : ["kbytes"]
        }
    ],
    "uptime" : [
        {
            "title" : "Uptime",
            "type" : "GAUGE",
            "args" : "--base 1000 -l 0",
            "fields" : ["uptime"]
        }
    ],
    "status" : [
        {
            "title" : "Status",
            "type" : "GAUGE",
            "args" : "--base 1000 -l 0",
            "fields" : ["busy", "idle"]
        }
    ]
}

if len(sys.argv) == 2 and sys.argv[1] == "autoconf":
    print "yes"
elif len(sys.argv) == 2 and sys.argv[1] == "config":
    if graph_type not in graph_types.keys():
        raise Exception("Unknown graph type '%s'"%graph_type)
    params = graph_types[graph_type]
    for item in params:
        print "graph_title %s" % item["title"]
        print "graph_category lighttpd"
        for field in item["fields"]:
            print "%s.label %s" % (field, field)
            print "%s.type %s" % (field, item["type"])
        print "graph_args %s" % item["args"]
elif len(sys.argv) == 2 and sys.argv[1] == "suggest":
    for item in graph_types.keys():
        print item
else:
    if "status-url" not in os.environ:
        status_url = "http://127.0.0.1/server-status"
    else:
        status_url = os.environ["status_url"]

    request = urllib2.Request("%s?auto" % status_url)
    if "username" in os.environ and "password" in os.environ:
        base64str = base64.encodestring("%s:%s" % (os.environ["username"], os.environ["password"])).replace("\r", "")
        request.add_header("Authorization", "Basic %s" % base64str)
    info = urllib2.urlopen(request).read()
    data = {}
    lines = info.split("\n")
    for line in lines:
        try:
           (title, value) = line.split(": ")
           data[title] = value
        except Exception:
           pass

    if graph_type == "accesses":
        print "accesses.value %s" % data["Total Accesses"]
    elif graph_type == "kbytes":
        print "kbytes.value %s" % data["Total kBytes"]
    elif graph_type == "uptime":
        print "uptime.value %s" % str(float(data["Uptime"])/86400)
    elif graph_type == "status":
        print "busy.value %s" % data["BusyServers"]
        print "idle.value %s" % data["IdleServers"]
