#!/opt/cloudlinux/venv/bin/python3 -bb
# coding=utf-8
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2020 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENCE.TXT
#

import csv
import os
import urllib.parse

from clcommon import cpapi
from sentry import init_wmt_sentry_client, setup_logger


domains_path = "/var/lve/wmt/domains.csv"


def write_domains():
    logger = setup_logger('write_domains')
    try:
        fd = os.open(domains_path,
                     os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW,
                     0o600)
        # Bugbot e2ae96c4: O_CREAT mode only applies on creation; chmod
        # ensures pre-existing files (mode 0644 from before this fix) get
        # the same restriction. Bugbot 22d06866: if fdopen fails, the
        # raw fd would leak — wrap and os.close on failure before re-raise.
        try:
            os.fchmod(fd, 0o600)
            csvfile = os.fdopen(fd, 'w', newline='')
        except Exception:
            os.close(fd)
            raise
        with csvfile:
            writer = csv.writer(csvfile)
            if cpapi.CP_NAME == cpapi.PLESK_NAME:
                users = [_cpinfo[0] for _cpinfo in cpapi.cpinfo(keyls=('cplogin',))]
            else:
                users = cpapi.cpusers()
            if not users:
                return
            domain_set = set()
            for user in users:
                try:
                    for domain, _ in cpapi.userdomains(user):
                        # Convert domain name to http://www.domain.com format
                        # https://stackoverflow.com/questions/21659044/how-can-i-prepend-http-to-a-url-if-it-doesnt-begin-with-http
                        p = urllib.parse.urlparse(domain, 'http')
                        netloc = p.netloc or p.path
                        path = p.path if p.netloc else ''
                        # Uncomment for http only
                        # p = urllib.parse.ParseResult('http', netloc, path, *p[3:])
                        p = urllib.parse.ParseResult(p.scheme, netloc, path, *p[3:])
                        url = p.geturl()
                        if url not in domain_set:
                            domain_set.add(url)
                            writer.writerow([url])
                except Exception as e:
                    logger.exception(e)
    except Exception as e:
        logger.exception(e)


if __name__ == "__main__":
    # execute only if run as a script
    init_wmt_sentry_client()
    write_domains()
