import sys
from os import getgid, getuid
from pathlib import Path
from pwd import getpwuid

from typer import confirm, prompt

from kolombo.console import debug, enable_debug, finished, info, started, step
from kolombo.util import run

_virtual_configs = {
    "addresses": "bob@example.com bob@example.com",
    "domains": "example.com",
    "mailbox": "bob@example.com bob@example.com/",
    "ssl_map": (
        "example.com /etc/letsencrypt/live/example.com/privkey.pem "
        "/etc/letsencrypt/live/example.com/fullchain.pem"
    ),
}


def init() -> None:
    from kolombo import __version__ as version

    username = getpwuid(getuid()).pw_name
    started(f"Setting up Kolombo for current user [b]{username}[/]")

    step("Creating /etc/kolombo folder ([u]need root privileges[/])")

    info("Creating /etc/kolombo folder (as root)")
    run(["mkdir", "-p", "-m", "750", "/etc/kolombo"], as_root=True)
    info(f"Changing /etc/kolombo owner to {username} (as root)")
    run(["chown", f"{getuid()}:{getgid()}", "/etc/kolombo"], as_root=True)

    step("Writing configuration to /etc/kolombo/kolombo.conf")
    debug_mode = confirm("Enable debug mode?", default=False, show_default=True)
    if debug_mode:
        enable_debug()

    nginx_secret_key: str = prompt(
        "Enter secret key for communication between NginX and auth API",
        default="changeme",
        show_default=True,
        hide_input=True,
        confirmation_prompt=True,
    )
    max_auth_attempts: int = prompt(
        "Enter maximum auth attempts per one session",
        default="3",
        show_default=True,
        type=int,
    )
    passwords_salt: str = prompt(
        "Enter secret key to be used as salt for passwords hashing",
        default="changeme",
        show_default=True,
        hide_input=True,
        confirmation_prompt=True,
    )
    configuration = (
        f"### Generated by kolombo v{version}\n\n"
        "# Whether debug mode is enabled (0 - disabled, 1 - enabled)\n"
        f"DEBUG={int(debug_mode)}\n"
        "# Secret key that is used to determine that nginx is using API\n"
        f"NGINX_SECRET_KEY={nginx_secret_key}\n"
        "# Maximum auth attempts per one session\n"
        f"MAX_ATTEMPTS={max_auth_attempts}\n"
        "# Salt used for passwords hashing\n"
        f"SALT={passwords_salt}\n"
    )
    with open("/etc/kolombo/kolombo.conf", "w") as config_file:
        config_file.write(configuration)

    step("Populating /etc/kolombo with default folders and files")
    debug("Creating /etc/kolombo folders for volumes")
    folders = ("maildirs", "mail-enabled", "virtual", "dkim_keys")
    for folder in folders:
        Path(f"/etc/kolombo/{folder}").mkdir(mode=0o770, exist_ok=True)

    for file in ("addresses", "domains", "mailbox", "ssl_map"):
        debug(f"Writing default file to /etc/kolombo/virtual/{file}")
        with open(f"/etc/kolombo/virtual/{file}", "w") as virtual_file:
            virtual_file.write(f"# {_virtual_configs[file]}\n")

    step("Installing auto-completion ([u]restart current shell session to use[/])")
    run([sys.argv[0], "--install-completion"])

    finished("Kolombo is set up!")
