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

#########################################################################
# 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
#########################################################################
import sys
import subprocess
from os.path import join, isabs, realpath
from subprocess import getstatusoutput
from pyeole.diagnose import CertValidator
from creole.client import CreoleClient


if __name__ == "__main__":
    client = CreoleClient()
    if client.get_creole('ad_local') == 'non':
        sys.exit(0)
    cmd = [". /usr/lib/eole/diagnose.sh", "len_pf_accent=$((len_pf+1))"]
    cert_file = subprocess.run(['lxc-attach', '-n', 'addc', '--', 'samba-tool', 'testparm', '--suppress-prompt', '--parameter-name', 'tls certfile'], capture_output=True).stdout.decode('utf-8').strip()
    if not isabs(cert_file):
        cert_file = realpath(join('/var/lib/samba/private/tls', cert_file))
    server_cert = '/var/lib/lxc/addc/rootfs' + cert_file

    expected_dns = client.get_creole('ad_server_fullname')
    cert = CertValidator(server_cert, cert_id='samba', expected_dns=expected_dns)
    cmd += cert.format_diagnostic(strict_dns=False)
    cmd.append('echo')
    cmd_string = "\n".join(cmd)
    err, ret = getstatusoutput(cmd_string)
    print(ret)
