import requests, argparse, CloudFlare, os, sys
import json

PROJECT_ROOT = os.path.abspath(os.path.join(
    os.path.dirname(__file__),
    os.pardir)
)
sys.path.append(PROJECT_ROOT)

import cloudflare.domains as domains

# get absolute paths
source = os.path.dirname(__file__)
parent = os.path.abspath(source + '/../')

# load vars file
vars_file = open(parent + '/email_server_vars.json')
server_vars = json.load(vars_file)
vars_file.close()

mailcowserver = server_vars['server_info']['mail_server']
mailcowtoken = server_vars['server_info']['mailcow_api_key']
domain_name = server_vars['server_info']['domain']
token = server_vars['dns_info']['cloudflare_api_key']

cf = CloudFlare.CloudFlare(token=token)


class Domain:
    def __init__(self, name):
        self.name = name
        self.description = 't'
        self.active = True
        self.alias_lmt = 5  # limit count of aliases associated with this domain
        self.mailbox_lmt = 25  # limit count of mailboxes associated with this domain
        self.defquota = 3072  # predefined mailbox quota in add mailbox form
        self.maxquota = 10240  # maximum quota per mailbox
        self.quota = 15240  # maximum quota for this domain (for all mailboxes in sum)
        self.rl_value = 10  # default rate limit value
        self.rl_frame = "s"  # enum
        self.backupmx = False
        self.relay_all_recipients = False
        self.restart_sogo = True  # restart SOGo after adding domain

    def __iter__(self):
        yield 'domain', self.name
        yield 'description', self.description
        yield 'aliases', self.alias_lmt
        yield 'mailboxes', self.mailbox_lmt
        yield 'quota', self.quota
        yield 'defquota', self.defquota
        yield 'maxquota', self.maxquota
        yield 'active', str(self.active * 1)
        yield 'rl_value', self.rl_value
        yield 'rl_frame', self.rl_frame
        yield 'backupmx', str(self.backupmx * 1)
        yield 'relay_all_recipients', self.relay_all_recipients
        yield 'restart_sogo', str(self.restart_sogo * 1)


if not domains.check_if_valid_domain(cf, domain_name):
    print("Invalid domain! Please add to cloudflare before continuing...")
    exit(1)

domain = Domain(name=domain_name)

api_url = 'https://' + mailcowserver + '/api/v1/'
request_url = api_url + 'add/domain/' + domain_name


# mailcow attempts to create certificates for mail.<server>, autodiscover, and autoconfig
# so we need to make sure these records exist before adding the domain
# def check_dns():
#     record_list = [domain_name]
#     for query in record_list:
#         try:
#             answers = dns.resolver.resolve(query)
#         except:
#             exit('DNS query name does not exist, did you run the create records script first? - exiting')
#         for rdata in answers:
#             print(rdata)


def create_domain():
    # check_dns()
    headers = {
        'Content-Type': 'application/json',
        'X-API-Key': mailcowtoken
    }
    response = requests.post(request_url, headers=headers, json=dict(domain))

    fmt_response = response.json()
    print(fmt_response)


def main():
    create_domain()


if __name__ == "__main__":
    main()
