import os
import shutil
import textwrap


def make_config_dir(domain, enough_dot_dir):
    os.environ['ENOUGH_DOT'] = str(enough_dot_dir)
    config_dir = f'{enough_dot_dir}/{domain}'
    if not os.path.exists(config_dir):
        os.makedirs(config_dir)
    return config_dir


def prepare_config_dir(domain, enough_dot_dir):
    os.environ['ENOUGH_DOMAIN'] = domain
    config_dir = make_config_dir(domain, enough_dot_dir)
    # Reuse existent SSH key. If it doesn't exist, then a key will be
    # generated by DotEnough.ensure_ssh_key.
    if os.path.isfile('infrastructure_key'):
        shutil.copy('infrastructure_key', f'{config_dir}/infrastructure_key')
        shutil.copy('infrastructure_key.pub', f'{config_dir}/infrastructure_key.pub')
    all_dir = f'{config_dir}/inventory/group_vars/all'
    if not os.path.exists(all_dir):
        os.makedirs(all_dir)
    shutil.copyfile('inventory/group_vars/all/clouds.yml', f'{all_dir}/clouds.yml')
    shutil.copyfile('inventory/group_vars/all/provision.yml', f'{all_dir}/provision.yml')
    open(f'{all_dir}/certificate.yml', 'w').write(textwrap.dedent(f"""\
    ---
    certificate_authority: letsencrypt_staging
    """))
    return config_dir
