#!/bin/bash /usr/scripts/python.sh
#-*- coding: utf-8 -*-
#
# check_cert_lc.py -- Affiche un avertissement lorsqu'un certificat
# stocké dans la base ldap va arriver à expiration au propriétaire de la
# machine à laquelle le certificat est attaché
#
# Copyright (c) 2014 Valentin Samir
# Authors: Valentin Samir <valentin.samir@crans.org>
#
# 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 time
import lc_ldap.shortcuts
from lc_ldap.objets import AssociationCrans

def get_certs(from_=None, to_=None):
    """retourne les certificats qui expire en `from_` et `days` jours plus tard.
    Par defaut, `from_`vautint(time.time())"""
    if from_ is None:
        from_ = int(time.time())
    if to_ is None:
        to_ = from_ + 21 * 3600 * 24
    conn = lc_ldap.shortcuts.lc_ldap_readonly()
    return conn.search(u"(&(xid=*)(end<=%s)(end>=%s))" % (to_, from_))

if __name__ == '__main__':
    proprio = {}
    now = time.time()
    # On récupère les cert quiqui expire entre 1970 et dans un an
    for cert in get_certs(from_=0, to_=int(now) + 24*3600*365):
        p = cert.machine().proprio()
        if isinstance(p, AssociationCrans):
            p_name = "Le Crans"
        else:
            p_name = str(p)
        if not p_name in proprio:
            proprio[p_name] = {}
        m_name = cert.machine()['host'][0]
        if not m_name in proprio[p_name]:
            proprio[p_name][m_name] = []
        proprio[p_name][m_name].append((round((int(cert['end'][0]) - now )/(3600.0*24), 0), cert))
    # On les trie par ordre d'expiration
    p_order = []
    m_order = []
    for p in proprio:
        for m in proprio[p]:
            proprio[p][m].sort()
            m_order.append((proprio[p][m][0][0], m))
    m_order.sort()
    cont = False
    for p in proprio:
        for (t,m) in m_order:
            if m in proprio[p] and not cont:
                p_order.append((t,p))
                cont = True
        cont = False
    p_order.sort()
    now = int(time.time())
    # Et on affiche tout ça sur stdout pour le moment
    for (t,p) in p_order:
        print "%s : " % p
        for (t, m) in m_order:
            if m in proprio[p]:
                print "    * %s" % m
                for (t, cert) in proprio[p][m]:
                    cert_name = cert["info"][0] if cert["info"] else ", ".join(str(h) for h in cert["hostCert"])
                    print "        * dans %s jours %s" % (t, cert_name)


