#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# CHECK_RID.PY -- Vérification et application de la correspondance rid <-> IP
#
# Copyright (c) 2010 Nicolas Dandrimont
# Authors: Nicolas Dandrimont <olasd@crans.org>
# Adapté par Pierre-Elliott Bécue pour cause de changement de schéma.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
sys.path.append('/usr/scripts/gestion')

from ridtools import Rid
from ldap_crans import crans_ldap

from optparse import OptionParser

def check_rid(normalize):
    """Vérifie que les rid correspondent bien aux IP.

    Si normalize = True, modifie la base pour que la correspondance
    soit bien vérifiée"""
    cl = crans_ldap()

    counter = 0
    s = cl.search("ipHostNumber=*")
    for m in s["machine"]:
        counter += 1
        rid = int(m.rid())
        ip = m.ip()
        try:
            rid_t = Rid(ipv4=ip)
        except ValueError, e:
            print e
        else:
            if rid != int(rid_t):
                print "%s: %s!=%s" % (m.Nom(), rid, int(rid_t))
                if normalize:
                    m.rid(int(rid_t))
    print counter

if __name__ == "__main__":
    parser = OptionParser()
    parser.set_defaults(normalize=False)
    parser.add_option("-n", "--normalize", action="store_true", help="Modifie les rid pour les faire conformer au schema")
    
    (options, args) = parser.parse_args()
    
    check_rid(options.normalize)
