<reponame>lub/Mailu<gh_stars>1-10
#!/usr/bin/python3

import os
import time
import subprocess

command = [
    "certbot",
    "-n", "--agree-tos", # non-interactive
    "-d", os.environ["HOSTNAMES"],
    "-m", "{}@{}".format(os.environ["POSTMASTER"], os.environ["DOMAIN"]),
    "certonly", "--standalone",
    "--cert-name", "mailu",
    "--preferred-challenges", "http", "--http-01-port", "8008",
    "--keep-until-expiring",
    "--rsa-key-size", "3072",
    "--config-dir", "/certs/letsencrypt",
    "--post-hook", "/config.py"
]

def format_for_nginx(fullchain, output):
    """ We may want to strip ISRG Root X1 out
    """
    certs = []
    with open(fullchain, 'r') as pem:
        cert = ''
        for line in pem:
            cert += line
            if '-----END CERTIFICATE-----' in line:
                certs += [cert]
                cert = ''
    with open(output, 'w') as pem:
        for cert in certs[:-1] if len(certs)>2 and os.getenv('LETSENCRYPT_SHORTCHAIN', default="False") else certs:
            pem.write(cert)

# if dane is used we recommend pinning to the key, so it should not change
# ('true','yes') to be consistent with the logic in configuration.py
if os.environ.get("TLS_REUSE_KEY", "false").lower() in ('true','yes'):
    command.append("--reuse-key")

# Wait for nginx to start
time.sleep(5)

# Run certbot every day
while True:
    subprocess.call(command)
    time.sleep(3600)
