from typing import Iterable


def generate_nginx_config(mx: str, domain: str, secret_key: str) -> str:
    from kolombo import __version__ as version

    return (
        f"### Generated by kolombo v{version}\n\n"
        "# IMAP (mail reading)\n"
        "server {\n"
        f"   server_name {mx};\n"
        f"   ssl_certificate /etc/letsencrypt/live/{mx}/fullchain.pem;\n"
        f"   ssl_certificate_key /etc/letsencrypt/live/{mx}/privkey.pem;\n"
        f"   auth_http_header X-Secret-Key {secret_key};\n"
        f"   auth_http_header X-Domain {domain};\n"
        f"   auth_http kolombo-auth:7089/auth;\n"
        "   listen 993 ssl;\n"
        "   protocol imap;\n"
        "}\n\n"
        "# POP3 (mail reading, use IMAP if possible)\n"
        "server {\n"
        f"   server_name {mx};\n"
        f"   ssl_certificate /etc/letsencrypt/live/{mx}/fullchain.pem;\n"
        f"   ssl_certificate_key /etc/letsencrypt/live/{mx}/privkey.pem;\n"
        f"   auth_http_header X-Secret-Key {secret_key};\n"
        f"   auth_http_header X-Domain {domain};\n"
        f"   auth_http kolombo-auth:7089/auth;\n"
        "   listen 995 ssl;\n"
        "   protocol pop3;\n"
        "}\n\n"
        "# Send-only SMTP\n"
        "server {\n"
        f"   server_name {mx};\n"
        f"   ssl_certificate /etc/letsencrypt/live/{mx}/fullchain.pem;\n"
        f"   ssl_certificate_key /etc/letsencrypt/live/{mx}/privkey.pem;\n"
        f"   auth_http_header X-Secret-Key {secret_key};\n"
        f"   auth_http_header X-Domain {domain};\n"
        f"   auth_http kolombo-auth:7089/auth;\n"
        "   listen 465 ssl;\n"
        "   protocol smtp;\n"
        "}\n"
    )


def generate_virtual_domains(domains: Iterable[str]) -> str:
    return "\n".join(domains)


def generate_virtual_ssl_map(mx_domains: Iterable[str]) -> str:
    return "\n".join(
        f"{mx} /etc/letsencrypt/live/{mx}/privkey.pem "
        f"/etc/letsencrypt/live/{mx}/fullchain.pem"
        for mx in mx_domains
    )


def generate_senders_compose_config(domains: Iterable[str]) -> str:
    compose_file = (
        # fmt: off
        "version: '3.8'\n"
        "services:\n"
        # fmt: on
    )
    for index, domain in enumerate(domains):
        compose_file += (
            f"  kolombo-{domain}-sender:\n"
            "     image: kolombo-sender:latest\n"
            "     tty: true\n"
            "     restart: always\n"
            f"     container_name: kolombo-{domain}-sender\n"
            f"     hostname: {domain}\n"
            "     volumes:\n"
            f"       - /etc/kolombo/dkim_keys/{domain}:/etc/opendkim/keys/{domain}\n"
            "     networks:\n"
            "       kolombo-net:\n"
            f"         ipv4_address: 192.168.79.{10 + index}\n"
            f"     command: {domain}\n\n"
        )

    compose_file += (
        # fmt: off
        "networks:\n"
        "  kolombo-net:\n"
        "    external: true\n"
        # fmt: on
    )
    return compose_file
