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

apply plugin: 'kotlin'
apply plugin: 'maven-publish'

apply from: rootProject.file('gradle/compile-options.gradle')

ext.configureKotlin()

dependencies {
    api "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    api project(":atomicfu-transformer")
    api "org.apache.maven:maven-core:$maven_version"
    api "org.apache.maven:maven-plugin-api:$maven_version"
    api 'org.apache.maven.plugin-tools:maven-plugin-annotations:3.5'
}

def outputDir = compileKotlin.destinationDirectory

publishing.publications {
    maven(MavenPublication) {
        MavenPomConfiguration.configureMavenPluginPomAttributes(pom, project, outputDir.get().getAsFile().path)
    }
}

String mavenUserHome = System.getProperty("maven.user.home")
String mavenRepoLocal = System.getProperty("maven.repo.local")

def pomFile = tasks.named("generatePomFileForMavenPublication", GenerateMavenPom).map { it.destination }.get()

// runs the plugin description generator
task generatePluginDescriptor(type: Exec, dependsOn: [generatePomFileForMavenPublication, ':atomicfu-transformer:publishToMavenLocal']) {
    def pluginDescriptorFile = outputDir.file('META-INF/maven/plugin.xml')

    workingDir projectDir
    boolean isWindows = System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0
    def args = isWindows ? ['cmd', '/c', 'mvnw.cmd'] : ['sh', './mvnw']
    if (mavenUserHome != null) args.add("-Dmaven.user.home=${new File(mavenUserHome).getAbsolutePath()}")
    if (mavenRepoLocal != null) args.add("-Dmaven.repo.local=${new File(mavenRepoLocal).getAbsolutePath()}")
    args.addAll([
            '--settings', './settings.xml',
            '--errors',
            '--batch-mode',
            '--file', pomFile.toString(),
            'org.apache.maven.plugins:maven-plugin-plugin:3.5.1:descriptor'
    ])
    commandLine args
    doLast {
        def descriptorFile = pluginDescriptorFile.get().getAsFile()
        assert descriptorFile, "$descriptorFile: was not generated"
        logger.info("Plugin descriptor is generated in $descriptorFile")
    }
}

project.jar.dependsOn(generatePluginDescriptor)
