#! /usr/bin/python
# -*- coding: iso-8859-1 -*-

# Hostname of Icecast server
# Just canonical name, no http:// nor ending /
host = "foo.bar.com"
username = "admin"
# Password for admin access to Icecast2 server to fetch statistics
password = ""
realm = "Icecast2 Server"

# This plugin shows the statistics of every source currently connected to the Icecast2 server. See the Icecast2_ plugin for specific mountpoint plugin.

import urllib2, os.path, time, sys
from xml.dom import minidom

def hent_XML():
    auth_handler = urllib2.HTTPBasicAuthHandler()
    auth_handler.add_password(realm, host, username, password)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)

    xmlweb = urllib2.urlopen("http://%s/admin/stats" % host)
    xml = xmlweb.read()
    xmlweb.close()

    # Parser oversikt

    xmldoc = minidom.parseString(xml)
    xmldoc = xmldoc.firstChild

    #Totalt antall lyttere
    total_lyttere = xmldoc.getElementsByTagName("clients")[0].firstChild.nodeValue
    #Totalt antall kilder
    total_kilder = xmldoc.getElementsByTagName("sources")[0].firstChild.nodeValue
    #Status for enkelt strøm
    sources = xmldoc.getElementsByTagName("source")
    sourcelist = {}
    for source in sources:
        mount = source.getAttribute("mount")
        listeners = source.getElementsByTagName("listeners")[0].firstChild.nodeValue
        name = source.getElementsByTagName("server_name")[0].firstChild.nodeValue
	mount = mount.replace("-", "_").replace(".", "_")
        sourcelist[mount[1:]] = (listeners, name)

    if len(sys.argv) > 0 and sys.argv[1] == "autoconf":
	print "yes"
    elif len(sys.argv) == 1 or sys.argv[1] != "config":
        print "totallyttere.value %s" % total_lyttere
        print "totalkilder.value %s" % total_kilder
	sourcesort = sourcelist.keys()
	sourcesort.sort()
        for source in sourcesort:
            listeners, name = sourcelist[source]
            print "%s.value %s" % (source, listeners)
    elif sys.argv[1] == "config":
        print "graph_title Total number of listeners"
        print "graph_vlabel listeners"
	print "graph_category streaming"
        print "totallyttere.label Total number of listeners"
        print "totalkilder.label Totalt number of sources"
	sourcesort = sourcelist.keys()
	sourcesort.sort()
	for source in sourcesort:
	    listeners, name = sourcelist[source]
	    print "%s.label %s" % (source, "/" + source)
    else:
        print sys.argv[1]


if __name__ == "__main__":
    hent_XML()
