/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import org.yaml.snakeyaml.Yaml

buildscript {
    repositories {
        if (hasProperty("centralRepo")) {
            maven {
                name "MavenCentral"
                url property("centralRepo")
            }
        } else {
            mavenCentral()
        }
    }

    dependencies {
        classpath 'org.yaml:snakeyaml:1.23'
    }
}

buildCache {
    local {
        directory = new File(rootDir, '.build-cache')
        removeUnusedEntriesAfterDays = 30
    }
}

// Synchronized library configuration for all modules
// This "componentsVersion" number is defined in ".buildconfig.yml" and should follow
// semantic versioning (MAJOR.MINOR.PATCH). See https://semver.org/
class Config {

    public final String componentsVersion
    public final String componentsGroupId
    public final Integer compileSdkVersion
    public final Integer minSdkVersion
    public final Integer targetSdkVersion

    Config(
        String componentsVersion,
        String componentsGroupId,
        Integer compileSdkVersion,
        Integer minSdkVersion,
        Integer targetSdkVersion
    ) {
        this.componentsVersion = componentsVersion
        this.componentsGroupId = componentsGroupId
        this.compileSdkVersion = compileSdkVersion
        this.minSdkVersion = minSdkVersion
        this.targetSdkVersion = targetSdkVersion
    }
}

def setupProject(name, path, description) {
    settings.include(":$name")

    project(":$name").projectDir = new File(rootDir, path)

    // project(...) gives us a skeleton project that we can't set ext.* on
    gradle.beforeProject { project ->
        // However, the "afterProject" listener iterates over every project and gives us the actual project
        // So, once we filter for the project we care about, we can set whatever we want
        if (project.name == name) {
            project.ext.description = description
        }
    }
}

def yaml = new Yaml()
def buildconfig = yaml.load(new File(rootDir, '.buildconfig.yml').newInputStream())
buildconfig.projects.each { project ->
    setupProject(project.key, project.value.path, project.value.description)
}

gradle.projectsLoaded { ->
    def configData = yaml.load(new File(rootDir, '.config.yml').newInputStream())
    String version = buildconfig.componentsVersion

    if (gradle.rootProject.hasProperty("nightlyVersion")) {
        version = gradle.rootProject.nightlyVersion
    }
    // To support local auto-publication workflow, we use a version prefix we wouldn't normally encounter.
    if (gradle.rootProject.hasProperty("local")) {
        version = "0.0.1"
    }
    // Wait until root project is "loaded" before we set "config"
    // Note that since this is set on "rootProject.ext", it will be "in scope" during the evaluation of all projects'
    // gradle files. This means that they can just access "config.<value>", and it'll function properly
    gradle.rootProject.ext.config = new Config(
        version,
        configData.componentsGroupId,
        configData.compileSdkVersion,
        configData.minSdkVersion,
        configData.targetSdkVersion
    )
    gradle.rootProject.ext.buildConfig = buildconfig
}

def runCmd(cmd, workingDir, successMessage) {
    def proc = cmd.execute(null, new File(workingDir))
    proc.consumeProcessOutput(System.out, System.err)
    proc.waitFor()
    if (proc.exitValue() != 0) {
        throw new GradleException("Process '${cmd}' finished with non-zero exit value ${proc.exitValue()}")
    } else {
        logger.lifecycle(successMessage)
    }
}

//////////////////////////////////////////////////////////////////////////
// Local Development overrides
//////////////////////////////////////////////////////////////////////////

Properties localProperties = null;
String settingAppServicesPath = "autoPublish.application-services.dir"
String settingGleanPath = "substitutions.glean.dir";

if (file('local.properties').canRead()) {
    localProperties = new Properties()
    localProperties.load(file('local.properties').newDataInputStream())
    logger.lifecycle('Local configuration: loaded local.properties')
} else {
    logger.lifecycle('Local configuration: absent local.properties; proceeding as normal.')
}

if (localProperties != null) {
    localProperties.each { prop ->
        gradle.ext.set("localProperties.${prop.key}", prop.value)
    }

    String appServicesLocalPath = localProperties.getProperty(settingAppServicesPath);

    if (appServicesLocalPath != null) {
        logger.lifecycle("Enabling automatic publication of application-services from: $appServicesLocalPath")
        // Windows can't execute .py files directly, so we assume a "manually installed" python,
        // which comes with a "py" launcher and respects the shebang line to specify the version.
        def publishAppServicesCmd = [];
        if (System.properties['os.name'].toLowerCase().contains('windows')) {
            publishAppServicesCmd << "py";
        }
        publishAppServicesCmd << "./automation/publish_to_maven_local_if_modified.py";
        runCmd(publishAppServicesCmd, appServicesLocalPath, "Published application-services for local development.")
    } else {
        logger.lifecycle("Disabled auto-publication of application-services. Enable it by settings '$settingAppServicesPath' in local.properties")
    }

    String gleanLocalPath = localProperties.getProperty(settingGleanPath);

    if (gleanLocalPath != null) {
        logger.lifecycle("Local configuration: substituting glean module from path: $gleanLocalPath")

        includeBuild(gleanLocalPath) {
            dependencySubstitution {
                substitute module('org.mozilla.telemetry:glean') with project(':glean')
                    substitute module('org.mozilla.telemetry:glean-forUnitTests') with project(':glean')
            }
        }
    } else {
        logger.lifecycle("Local configuration: glean substitution path missing. You may specify it via '$settingGleanPath' setting.")
    }
}
