/*
 * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

import org.jetbrains.kotlin.konan.target.HostManager

buildscript {
    def overridingKotlinVersion = KotlinConfiguration.getOverridingKotlinVersion(project)
    if (overridingKotlinVersion != null) { project.kotlin_version = overridingKotlinVersion }

    /*
     * This property group is used to build kotlinx.atomicfu against Kotlin compiler snapshots.
     * When build_snapshot_train is set to true, kotlin_version property is overridden with kotlin_snapshot_version.
     * Additionally, mavenLocal and Sonatype snapshots are added to repository list
     * (the former is required for AFU and public, the latter is required for compiler snapshots).
     * DO NOT change the name of these properties without adapting kotlinx.train build chain.
     */
    def buildSnapshotTrainGradleProperty = project.findProperty("build_snapshot_train")
    ext.build_snapshot_train = buildSnapshotTrainGradleProperty != null && buildSnapshotTrainGradleProperty != ""
    if (build_snapshot_train) {
        project.kotlin_version = project.findProperty("kotlin_snapshot_version")
        if (project.kotlin_version == null) {
            throw new IllegalArgumentException("'kotlin_snapshot_version' should be defined when building with a snapshot compiler")
        }
        repositories {
            maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
        }
    }

    repositories {
        mavenCentral()
        gradlePluginPortal()
        KotlinConfiguration.addCustomKotlinRepositoryIfEnabled(delegate, project)
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.github.node-gradle:gradle-node-plugin:$gradle_node_version"
    }

    ext.native_targets_enabled = !project.hasProperty("disable_native_targets")
}

plugins {
    id 'org.jetbrains.kotlinx.binary-compatibility-validator' version '0.13.2'
}

allprojects {
    // the only place where HostManager could be instantiated
    project.ext.hostManager = new HostManager()

    def overridingKotlinVersion = KotlinConfiguration.getOverridingKotlinVersion(project)
    if (overridingKotlinVersion != null) { project.kotlin_version = overridingKotlinVersion }

    if (build_snapshot_train) {
        project.kotlin_version = project.findProperty("kotlin_snapshot_version")
        repositories {
            maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
        }
    }

    logger.info("Using Kotlin compiler ${project.kotlin_version} for project ${project.name}")

    repositories {
        mavenCentral()
        KotlinConfiguration.addCustomKotlinRepositoryIfEnabled(delegate, project)
    }

    def deployVersion = project.findProperty("DeployVersion")
    if (deployVersion != null) project.version = deployVersion

    // atomicfu-native check is a kludge so that existing YouTrack config works, todo: remove
    if (project != rootProject && project.name != "atomicfu-native") {
        apply from: rootProject.file("gradle/publishing.gradle")
    }

    // this fixes "org.gradle.jvm.version" in Gradle metadata
    plugins.withType(JavaPlugin).configureEach {
        java {
            toolchain {
                languageVersion.set(JavaLanguageVersion.of(8))
            }
        }
    }

    tasks.withType(org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile).configureEach {
        compilerOptions { freeCompilerArgs.add("-Xpartial-linkage-loglevel=ERROR") }
    }
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinNativeCompile).configureEach {
        compilerOptions { freeCompilerArgs.add("-Xpartial-linkage-loglevel=ERROR") }
    }
}

if (build_snapshot_train) {
    afterEvaluate {
        println "Manifest of kotlin-compiler-embeddable.jar for atomicfu"
        configure(subprojects.findAll { it.name == "atomicfu" }) {
            configurations.matching { it.name == "kotlinCompilerClasspath" }.configureEach {
                resolvedConfiguration.getFiles().findAll { it.name.contains("kotlin-compiler-embeddable") }.each {
                    def manifest = zipTree(it).matching {
                        include 'META-INF/MANIFEST.MF'
                    }.getFiles().first()

                    manifest.readLines().each {
                        println it
                    }
                }
            }
        }
    }
}

// main deployment task
task deploy(dependsOn: getTasksByName("publish", true) + getTasksByName("publishNpm", true))

// Right now it is used for switching nodejs version which is supports generated wasm bytecode
extensions.findByType(org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension.class).with {
    // canary nodejs that supports recent Wasm GC changes
    it.nodeVersion = '21.0.0-v8-canary202309167e82ab1fa2'
    it.nodeDownloadBaseUrl = 'https://nodejs.org/download/v8-canary'
}

// We need to ignore unsupported engines (i.e. canary) for npm
tasks.withType(org.jetbrains.kotlin.gradle.targets.js.npm.tasks.KotlinNpmInstallTask).configureEach {
    args.add("--ignore-engines")
}
