#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#########################################################################
# pyeole.service - manage EOLE services
# Copyright © 2022 Pôle de Compétence EOLE <eole@ac-dijon.fr>
#
# License CeCILL:
#  * in french: http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html
#  * in english http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
#########################################################################
from creole.client import CreoleClient
from os.path import isfile, basename
from pyeole.diagnose import CertValidator, list_certificats
from zephir.monitor.agentmanager.config import CERT_TYPE, SERVER_CERT, SERVER_PEM, LE_CERTIFICATES
from pyeole.process import system_out
from subprocess import getstatusoutput



if __name__ == "__main__":
    cmd = [". /usr/lib/eole/diagnose.sh", "len_pf_accent=$((len_pf+1))", 'EchoGras "*** Validité des certificats"']
    cert_db = list_certificats(SERVER_PEM, SERVER_CERT, CERT_TYPE, LE_CERTIFICATES)
    client = CreoleClient()
    cert_type = client.get_creole('cert_type')
    expected_dns = client.get_creole('ssl_subjectaltname')
    expected_dns.append(client.get_creole('ssl_server_name'))
    expected_dns = list(set(expected_dns))
    for cert_file, cert_datas in cert_db.items():
        if cert_datas.get('type') == 'letsencrypt':
            exp_dns = None
        else:
            exp_dns = expected_dns
        cert = CertValidator(cert_file, cert_id=cert_file, chain=cert_datas['chain'], ca=cert_datas['ca'], expected_dns=exp_dns, usage=cert_datas.get("usage"))
        cmd += cert.format_diagnostic(strict_dns=True)
        if cert_type == 'letsencrypt':
            if isfile("/var/lib/eole/reports/letsencrypt.err"):
                cmd.append('EchoRouge "Erreur à la demande du certificat, des logs sont disponibles'
                           + 'dans le fichier /var/log/eole-letsencrypt.log')

    cmd.append('echo')
    cmd_string = "\n".join(cmd)
    err, ret = getstatusoutput(cmd_string)
    print(ret)
