#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-

"""
Mise a jour periodique des listes d'ip et d'id disponibles.

Copyright (C) Alexandre Bos, largement pompe sur ldap_crans.py
Licence : GPLv2
"""

import sys
from config import NETs
from iptools import AddrInNet
import netaddr

try:
    from dialog import Dialog
except ImportError:
    Dialog = None

repertoire =  '/usr/scripts/var/numeros_disponibles/'

def lister_ip_dispo(plage):
    f = open(repertoire + 'ip_' + plage)
    lignes = f.readlines()
    liste = []
    for l in lignes:
        liste.append(l.strip())
    return liste

def lister_ip_utilisees():
    liste = []
    from ldap_crans import crans_ldap
    db = crans_ldap()
    r = db.search('mid=*')
    machines = r['machineFixe'] + r['machineWifi'] + r['machineCrans'] + r['borneWifi']
    for m in machines:
        liste.append(m.ip())
    return liste

def update_ip(plage, occupees):
    net = NETs[plage]
    pool_ip = []                # Pool d'IP à tester
    for ne in net:
        ne = netaddr.IPNetwork(ne)
        for ip in ne:
            # avoid .255 and .0 (even for non-/24 nets)
            if (ip.value & 255) in [0,255]:
                continue
            pool_ip.append(str(ip))

    resultat = ''.join('%s\n' % ip for ip in pool_ip if ip not in occupees)

    f = open(repertoire + 'ip_' + plage,'w')
    f.write(resultat)
    f.close

def update_ip_fixe(occupees):
    update_ip('fil', 'ip_fil', occupees)

def update_ip_wifi_adh(occupees):
    update_ip('wifi-adh','ip_wifi-adh', occupees)

TO_COMPUTE = [
    'wifi',
    'wifi-adh',
    'serveurs',
    'adherents',
    'bornes',
    'adm',
    'personnel-ens',
    'fil',
]

if __name__ == "__main__":
    if "--cron" in sys.argv:
        cron = True
    else:
        cron = False
    if not cron:
        dlg = Dialog()
        dlg.gauge_start(text="Recherche des machines...", backtitle="numeros_disponibles")
    ip_occupees = lister_ip_utilisees()
    done = 1
    for net in TO_COMPUTE:
        if not cron:
            dlg.gauge_update(int(done*100/(len(TO_COMPUTE)+1)), text="IP libres dans %s" % net, update_text=True)
        update_ip(net, ip_occupees)
        done += 1
    if not cron:
        dlg.gauge_update(100, text="Fini !", update_text=True)
        dlg.gauge_stop()
