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

# Génération d'un fichier XML indiquant le status des bornes

import sys, os, time, optparse
sys.path.append("/usr/scripts/gestion")
sys.path.append("/usr/scripts/wifi")

### parsing
parser = optparse.OptionParser(usage="usage: %prog [-o FILE]")
parser.add_option('-o', '--output', help=u"outputs to FILE",
                  metavar='FILE', dest="filename")
(options, args) = parser.parse_args()

from bornes import bornes_canal, bornes_clients, bornes_uptime

from ldap_crans import crans_ldap
l = crans_ldap()

import xml.dom.minidom

# création objet xml
status=xml.dom.minidom.Document()

xml_bornes=status.createElement(u"bornes")
status.appendChild(xml_bornes)
xml_bornes.setAttribute(u"date",time.strftime("%c"))

# On récupère l'ensemble des bornes
bornes = l.search('host=*.wifi.crans.org&canal=*')['borneWifi']
bornes.sort(cmp=(lambda x, y: cmp(x.nom(), y.nom())))

canaux = bornes_canal()
clients = bornes_clients()
uptimes = bornes_uptime()

for b in bornes:
    infos = filter(lambda x: not x.startswith("<"), b.info())
    if not infos or b.nom().split('.')[0]=="non-configure":
        # Rien à propos de cette borne...
        continue

    # Est-ce un hotspot ?
    hotspot = b.hotspot() and 1 or 0
    # Est-ce que la borne est up ?
    if os.system("/usr/bin/fping -q %s 2> /dev/null" % b.nom()) == 0:
        up = 1
    else:
        up = 0
    # Quel nom ?
    nom = b.nom().split(".")[0]
    xml_borne=status.createElement(u"borne")
    xml_borne.setAttribute(u"nom",nom)
    xml_borne.setAttribute(u"hotspot",unicode(hotspot))
    xml_borne.setAttribute(u"up",unicode(up))

    xml_desc=status.createElement(u"description")
    xml_desc.appendChild(status.createTextNode(infos[0]))
    #xml_desc.appendChild(status.createTextNode(u"Description pas compatible unicode/ascii"))
    xml_borne.appendChild(xml_desc)
    xml_mac=status.createElement(u"mac")
    xml_mac.appendChild(status.createTextNode(b.mac2()))
    xml_borne.appendChild(xml_mac)

    # Certains résultats (ragnarok) n'ont pas tous les champs.
    if (canaux.has_key(nom)):
        xml_canal=status.createElement(u"canal")
        try:                canal = unicode(int(canaux[nom]))
        except TypeError:  canal = u'Inconnu'
        xml_canal.appendChild(status.createTextNode(canal))
        xml_borne.appendChild(xml_canal)

    if (clients.has_key(nom)):
        xml_clients=status.createElement(u"clients")
        try: client = unicode(int(clients[nom]))
        except TypeError: client = u'Inconnu'
        xml_clients.appendChild(status.createTextNode(client))
        xml_borne.appendChild(xml_clients)

    if (uptimes.has_key(nom)):
        xml_uptime=status.createElement(u"uptime")
        xml_uptime.appendChild(status.createTextNode(unicode(uptimes[nom])))
        xml_borne.appendChild(xml_uptime)

    position = b.position()
    if position:
        xml_position=status.createElement(u"position")
        xml_position.setAttribute(u"x",unicode(position[1]))
        xml_position.setAttribute(u"y",unicode(position[0]))
        xml_borne.appendChild(xml_position)

    xml_bornes.appendChild(xml_borne)

if options.filename:
    f = open(options.filename, 'w')
    f.write(status.toxml().encode("UTF-8"))
    f.close()
else:
    print (status.toxml().encode("UTF-8"))
