#!/usr/bin/env python3

"""
Meh mail client conf generator for other things
"""

import configparser
import os
import sys

# TODO Find config file from XDG
# TODO Alias adresses
# TODO Signature file
# TODO Write ~/.mail/[mailbox]/color file if required by sth?
# Certificate file

configPath = os.path.join(os.path.expanduser('~'), '.config', 'mel.conf')

config = configparser.ConfigParser()
config.read(configPath)

SERVER_DEFAULTS = {
            "imap": {"port": 143, "starttls": True},
            "smtp": {"port": 587, "starttls": True},
        }
SERVER_ITEMS = {"host", "port", "user", "pass", "starttls"}

# Reading sections
accounts = dict()

for name in config.sections():
    if not name.islower():
        continue
    section = config[name]

    data = dict()
    for server in SERVER_DEFAULTS.keys():
        for item in SERVER_ITEMS:
            key = server + item
            try:
                val = section.get(key) or section.get(item) or SERVER_DEFAULTS[server][item]
            except KeyError:
                raise KeyError("{}.{}".format(name, key))

            if isinstance(val, str):
                if val == "True":
                    val = True
                elif val == "False":
                    val = False
                elif val.isnumeric():
                    val = int(val)
            data[key] = val

    for key in section.keys():
        if key in SERVER_ITEMS:
            continue
        data[key] = section[key]

    data["name"] = name
    data["storage"] = os.path.join(config['GLOBAL']['storage'], name)
    data["storageInbox"] = os.path.join(data["storage"], "INBOX")
    storageFull = os.path.expanduser(data["storage"])
    os.makedirs(storageFull, exist_ok=True)
    accounts[name] = data

# OfflineIMAP

OFFLINEIMAP_BEGIN = """[general]
# List of accounts to be synced, separated by a comma.
accounts = {}
maxsyncaccounts = {}
stocktimeout = 60
pythonfile = ~/.config/offlineimap.py

[mbnames]
enabled = yes
filename = ~/.mutt/mailboxes
header = "mailboxes "
peritem = "+%(accountname)s/%(foldername)s"
sep = " "
footer = "\\n"

"""

OFFLINEIMAP_ACCOUNT = """[Account {name}]
localrepository = {name}-local
remoterepository = {name}-remote
autorefresh = 0.5
quick = 10
utf8foldernames = yes
postsynchook = ~/.mutt/postsync

[Repository {name}-local]
type = Maildir
localfolders = {storage}

[Repository {name}-remote]
type = IMAP
{secconf}
keepalive = 60
holdconnectionopen = yes
remotehost = {imaphost}
remoteport = {imapport}
remoteuser = {imapuser}
remotepass = {imappass}

"""

offlineIMAPstr = OFFLINEIMAP_BEGIN.format(','.join(accounts), len(accounts))
for name, account in accounts.items():
    if account["imapstarttls"]:
        secconf = "ssl = no"
    else:
        secconf = "sslcacertfile = /etc/ssl/certs/ca-certificates.crt"
    offlineIMAPstr += OFFLINEIMAP_ACCOUNT.format(**account, secconf=secconf)
# TODO Write

# mbsync
MBSYNC_ACCOUNT = """IMAPAccount {name}
Host {imaphost}
User {imapuser}
Pass "{imappass}"
{secconf}

IMAPStore {name}-remote
Account {name}

MaildirStore {name}-local
Subfolders Verbatim
Path {storage}/
Inbox {storageInbox}/

Channel {name}
Master :{name}-remote:
Slave :{name}-local:
Patterns *
Create Both
SyncState *

"""

mbsyncStr = ""
for name, account in accounts.items():
    if account["imapstarttls"]:
        secconf = "SSLType STARTTLS"
    else:
        secconf = "SSLType IMAPS"
    mbsyncStr += MBSYNC_ACCOUNT.format(**account, secconf=secconf)
msbsyncFilepath = os.path.join(os.path.expanduser('~'), '.mbsyncrc')
with open(msbsyncFilepath, 'w') as f:
    f.write(mbsyncStr)

# msmtp
MSMTP_BEGIN = """defaults
protocol smtp
auth on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

"""

MSMTP_ACCOUNT = """account {name}
from {from}
user {smtpuser}
password {smtppass}
host {smtphost}
port {smtpport}
tls on

"""

msmtpStr = MSMTP_BEGIN
for name, account in accounts.items():
    msmtpStr += MSMTP_ACCOUNT.format(**account)
msbsyncFilepath = os.path.join(os.path.expanduser('~'), '.msmtprc')
with open(msbsyncFilepath, 'w') as f:
    f.write(msmtpStr)