#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import requests
import subprocess
import datetime
import logging
logger = logging.getLogger(__name__)

SOURCES = os.environ.get("SOURCES")
RESOURCES = os.environ.get("RESOURCES")
SAAS_PROVIDER_URL = os.environ.get("SAAS_PROVIDER_URL")
SAAS_PROVIDER_TOKEN = os.environ.get("SAAS_PROVIDER_TOKEN")
DOCKER_REPO = os.environ.get("DOCKER_REPO")
DOCKER_TAG_SUFFIX = os.environ.get("DOCKER_TAG_SUFFIX")
ODOO_VERSION = os.environ.get("ODOO_VERSION")


def wget(url, output, force=True, params=None):
    r = requests.get(url, params=params,verify=False)
    if r.status_code != 200:
        raise Exception("Unable to GET %s [%s] (%s)" % (
            url, params, r.status_code))
    if os.path.exists(output):
        if not force:
            raise Exception("File already exists")
        else:
            os.remove(output)
    if not r.content:
        logger.warning("GET %s [%s] returned an empty file" % (url, params))
        return False
    with open(output, 'wb') as file:
        file.write(r.content)
    return output


def wget_saas_file(url, output, extra_params=None):
    base_url = "%s/odoo_project" % SAAS_PROVIDER_URL
    params = {
        "docker_image": DOCKER_REPO,
        "major_version": ODOO_VERSION,
        "suffix": DOCKER_TAG_SUFFIX,
        "token": SAAS_PROVIDER_TOKEN,
    }
    if extra_params:
        params.update(extra_params)
    return wget("%s/%s" % (base_url, url), output, params=params)


if SAAS_PROVIDER_URL:
    # Create repos.d if it's missing
    if not os.path.isdir(os.path.join(RESOURCES, "repos.d")):
        os.makedirs(os.path.join(RESOURCES, "repos.d"))
    # Get files
    wget_saas_file(
        "repos.yml",
        os.path.join(RESOURCES, "repos.d", "saas-repos.yml"),
    )
    wget_saas_file(
        "repos.yml",
        os.path.join(RESOURCES, "repos.d", "saas-version-repos.yml"),
        extra_params={
            "minor_version": datetime.datetime.now().strftime("%Y.%m.%d"),
        },
    )
    wget_saas_file(
        "custom.conf",
        os.path.join(RESOURCES, "conf.d", "900-saas.conf"),
    )
    wget_saas_file(
        "entrypoint",
        os.path.join(RESOURCES, "entrypoint.d", "900-saas-entrypoint"),
    )
    wget_saas_file(
        "build",
        os.path.join(RESOURCES, "saas_build"),
    )
    # Aggregate repositories. We simply call that build step manually
    subprocess.check_call(
        [os.path.join(RESOURCES, "build.d", "300-aggregate-repositories")])
    subprocess.check_call(
        ["chown", "-R", "odoo.odoo", os.path.join(SOURCES, "repositories")])
    # Set permissions
    subprocess.check_call(["chown", "-R", "odoo.odoo", RESOURCES])
    if os.path.isfile(os.path.join(RESOURCES, "entrypoint.d", "900-saas-entrypoint")):
        subprocess.check_call(
            ["chmod", "a+x", os.path.join(RESOURCES, "entrypoint.d", "900-saas-entrypoint")])
    # Run custom build script
    if os.path.isfile(os.path.join(RESOURCES, "saas_build")):
        subprocess.check_call(
            ["chmod", "a+x", os.path.join(RESOURCES, "saas_build")])
        subprocess.check_call([os.path.join(RESOURCES, "saas_build")])
