import __main__
from subprocess import run as _run
from os.path import join as _join, isfile as _isfile, isdir as _isdir
from datetime import datetime as _datetime
from shutil import copyfile as _copyfile
from os import makedirs as _makedirs, environ as _environ, listdir as _listdir, unlink as _unlink


_HERE = _environ['PWD']
_LE_DIR = _join(_HERE, 'pki', 'letsencrypt')
_X509_DIR = _join(_HERE, 'pki', 'x509')


def letsencrypt_certif(domain: str,
                       authority_cn: str,
                       plugin_name: str,
                       credential_filename: str,
                       email: str,
                       hide_secret: bool,
                       ) -> None:
    if hide_secret:
        return
    if None in (domain, authority_cn, plugin_name, credential_filename, email):
        return
    authority_name = 'External'
    date_file = _join(_LE_DIR, f'{domain}.date')
    date = _datetime.now()
    today = str(date.date())
    if not _isfile(date_file):
        letsencrypt_date = '0'
    else:
        with open(date_file, 'r') as fh:
            letsencrypt_date = fh.read().strip()
    if letsencrypt_date != today:
#        print(f"Obtain or renew Let's Encrypt certificate for {domain}...")
        cli_args = ['certbot',
                    'certonly',
                    f'--dns-{plugin_name}',
                    f'--dns-{plugin_name}-credentials',
                    credential_filename,
                    '-d',
                    domain,
                    '--quiet',
                    '--config-dir', 
                    f'{_LE_DIR}/{domain}/config',
                    '--work-dir',
                    f'{_LE_DIR}/{domain}/work',
                    '--logs-dir',
                    f'{_LE_DIR}/{domain}/logs',
                    '--agree-tos',
                    '-m',
                    email,
                    '--dns-ovh-propagation-seconds',
                    '360',
                    ]
        ret = _run(cli_args, capture_output=True)
        #if ret.returncode != 0:
        #    print("FIXME")
            #raise ValueError(ret.stderr.decode())
#        print("Done")
    with open(date_file, 'w') as fh:
        fh.write(today)
    rootdir = _join(_X509_DIR, f'{authority_name}+{authority_cn}')
    certdir = _join(rootdir, 'certificats', domain, 'server')
    chaindir = _join(rootdir, 'certificats', domain, 'ca')
    week_number = date.isocalendar().week
    for dirname in (chaindir, certdir):
        if not _isdir(dirname):
            _makedirs(dirname)
    certificate_name = f'certificate_{week_number}.crt'
    _copyfile(_join(_LE_DIR, domain, 'config/live', domain, 'chain.pem'),
              _join(chaindir, certificate_name),
              )
    _copyfile(_join(_LE_DIR, domain, 'config/live', domain, 'privkey.pem'),
              _join(certdir, 'private.key'),
              )
    _copyfile(_join(_LE_DIR, domain, 'config/live', domain, 'fullchain.pem'),
              _join(certdir, certificate_name),
              )
    for dirname in (chaindir, certdir):
        for filename in _listdir(dirname):
            if not filename.endswith('.crt') or filename == certificate_name:
                continue
            _unlink(_join(dirname, filename))
