import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.github.blindpirate.gogradle.TestTop1000Task

/************** plugins **************/
plugins {
    id 'java'
    id 'groovy'
    id 'idea'
    id 'checkstyle'
    id 'jacoco'
    id 'antlr'
    id 'codenarc'
    id 'com.github.kt3k.coveralls' version '2.7.1'
    id 'com.github.johnrengelman.shadow' version '4.0.3'
    id "com.gradle.plugin-publish" version "0.9.9"
    id "co.riiid.gradle" version "0.4.2"
    id "org.jetbrains.kotlin.jvm" version "1.3.72"
    id "com.github.spotbugs" version "4.0.5"
}

println System.getenv("PATH")
apply from: 'config/scripts/coverage.gradle'

group 'com.github.blindpirate'
version '0.11.4'
sourceCompatibility = '1.8'
targetCompatibility = '1.8'

/************** sourcesets **************/
sourceSets {
    // Note that just declaring this sourceset creates two configurations.
    main {
        java {
            srcDirs += ['src/main/antlr']
        }
    }
    integrationTest {
        java.srcDirs = []
        groovy.srcDirs = ['src/integration-test/groovy']
        kotlin.srcDirs = []
        resources.srcDirs = ['src/integration-test/resources']
    }
    crossVersionTest {
        java.srcDirs = []
        groovy.srcDirs = []
        kotlin.srcDirs = ['src/cross-version-test/kotlin']
        resources.srcDirs = ['src/cross-version-test/resources']
    }
}

/************** dependencies **************/
repositories {
    mavenLocal()
    jcenter()
}
dependencies {
    integrationTestCompile sourceSets.main.output
    integrationTestCompile sourceSets.test.output
    integrationTestCompile configurations.testCompile
    integrationTestRuntime configurations.testRuntime

    crossVersionTestCompile sourceSets.main.output
    crossVersionTestCompile sourceSets.test.output
    crossVersionTestCompile sourceSets.integrationTest.output
    crossVersionTestCompile configurations.testCompile

    antlr "org.antlr:antlr4:4.6"

    compile gradleApi()
    compile "org.antlr:antlr4:4.6"
    compile group: 'com.google.inject', name: 'guice', version: '4.1.0'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.5'
    compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.1'
    compile group: 'commons-codec', name: 'commons-codec', version: '1.10'
    compile group: 'commons-io', name: 'commons-io', version: '2.5'
    compile 'com.google.guava:guava:20.0'
    compile 'com.github.zafarkhaja:java-semver:0.9.0'
    compile group: 'org.jsoup', name: 'jsoup', version: '1.7.2'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'
    compile 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.5'
    compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.8.5'
    compile group: 'com.google.code.findbugs', name: 'annotations', version: '3.0.1'
    compile group: 'net.lingala.zip4j', name: 'zip4j', version: '1.3.2'
    compile group: 'org.apache.ant', name: 'ant', version: '1.10.0'
    compile group: 'com.typesafe.sbt', name: 'sbt-interface', version: '0.13.13'
    compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.6.3'
    compile group: 'org.codehaus.woodstox', name: 'woodstox-core-asl', version: '4.4.1'
    compile group: 'org.jooq', name: 'joor', version: '0.9.6'
    compile 'com.moandjiezana.toml:toml4j:0.7.2'

    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile group: 'com.github.stefanbirkner', name: 'system-rules', version: '1.16.1'
    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.23.0'
    testCompile group: 'org.eclipse.jgit', name: 'org.eclipse.jgit', version: '4.5.3.201708160445-r'
    testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version: '9.4.2.v20170220'
    testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version: '9.4.2.v20170220'
    testCompile group: 'org.eclipse.jgit', name: 'org.eclipse.jgit.http.server', version: '4.5.3.201708160445-r'

    integrationTestCompile 'com.github.tomakehurst:wiremock:2.19.0'
    integrationTestCompile 'org.apache.commons:commons-exec:1.3'

    crossVersionTestCompile 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
    crossVersionTestCompile 'org.jetbrains.kotlin:kotlin-test-junit'
    crossVersionTestCompile 'org.jetbrains.kotlin:kotlin-test'
    crossVersionTestCompile 'org.jetbrains.kotlin:kotlin-reflect'
    crossVersionTestCompile gradleTestKit()
}
/************** test **************/
// Define integration test task
createIntegrationTest('integrationTest', 'integrationTest')

List<String> gradleVersionsToBeTested = JavaVersion.current().isJava9Compatible()
        ? ["4.8.1", "4.9", "4.10.3", "5.0"]
        : ["3.5.1", "4.0.1", "4.1", "4.2.1", "4.3.1", "4.4.1", "4.5.1", "4.6", "4.7", "4.8.1", "4.9", "4.10.3", "5.0"]

gradleVersionsToBeTested.each {
    def testTask = createIntegrationTest("gradle${it}CrossVersionTest", 'crossVersionTest')
    testTask.systemProperty('test.gradle.version', it)
    testTask.mustRunAfter 'integrationTest'
}

def createIntegrationTest(String taskName, String sourceSet) {
    project.tasks.create(name: taskName, type: Test) {
        if (gradle.gradleVersion.startsWith('4.') || gradle.gradleVersion.startsWith("5.") || gradle.gradleVersion.startsWith("6.")) {
            testClassesDirs = sourceSets[sourceSet].output.classesDirs
        } else {
            testClassesDir = sourceSets[sourceSet].output.classesDir
        }
        classpath = sourceSets[sourceSet].runtimeClasspath
        dependsOn 'shadowJar'
        mustRunAfter 'test'
    }
}

project.tasks.withType(Test) {
    mustRunAfter spotbugsMain, spotbugsTest, spotbugsIntegrationTest, spotbugsCrossVersionTest
    if (gradle.startParameter.isOffline()) {
        it.systemProperty("TEST_ARE_OFFLINE", 'true')
    }
    it.systemProperty("GRADLE_DIST_HOME", gradle.gradleHomeDir)
    it.systemProperty('GOGRADLE_ROOT', rootDir.absolutePath.replace('\\', '/'))
    check.dependsOn(it)
}

check.dependsOn javadoc, jacocoTestReport

/************** testTop1000 **********/

task testOne(type: TestTop1000Task) {
    doLast {
        testOne("${testProjectDir}")
    }
}
task testAll(type: TestTop1000Task) {
    doLast {
        testAll("${allTestProjectsDir}")
    }
}

/************** checkstyle **************/

checkstyle {
    toolVersion = '6.7'
}

checkstyleTest {
    enabled = false
}

/************** javadoc **************/

javadoc {
    options.addStringOption('encoding', 'UTF-8')
}

/************** coverage **************/

jacoco {
    toolVersion = "0.8.5"
}
jacocoTestReport {
    reports {
        xml.enabled = true // coveralls plugin depends on xml format report
        html.enabled = true
    }
    afterEvaluate {
        classDirectories.setFrom(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude:
                            ['com/github/blindpirate/gogradle/antlr/**',
                             'com/github/blindpirate/gogradle/core/exceptions/**',
                             'com/github/blindpirate/gogradle/vcs/bazaar/**',
                             'com/github/blindpirate/gogradle/vcs/svn/**',
                             'com/github/blindpirate/gogradle/util/HttpUtils*',
                             'com/github/blindpirate/gogradle/util/IOUtils*'])
        })
    }
}

jacocoTestReport.dependsOn 'test', 'integrationTest'
//check.dependsOn 'coverageCheck'

/************** antlr **************/
generateGrammarSource {
    // WARNING: DO NOT put source files here, every time this task executed, this directory will be overwritten
    // Don't ask me how I know it.  T^T
    outputDirectory = file('src/main/antlr/com/github/blindpirate/gogradle/antlr')
    arguments += ['-package', 'com.github.blindpirate.gogradle.antlr']
}

/************** publish **************/
def updateVersion(String file, String oldVersionRegex, String newVersion) {
    String content = new File(rootDir, file).getText()
    content = content.replaceAll(oldVersionRegex, newVersion)
    new File(rootDir, file).write(content)
}

task('updateVersion') {
    doLast {
        updateVersion('docs/build-go-with-gradle.md', /id 'com.github.blindpirate.gogradle' version '(\w|\d|\.|\-)*'/, "id 'com.github.blindpirate.gogradle' version '${version}'")
        updateVersion('docs/build-go-with-gradle-en.md', /id 'com.github.blindpirate.gogradle' version '(\w|\d|\.|\-)*'/, "id 'com.github.blindpirate.gogradle' version '${version}'")
        updateVersion('docs/getting-started-cn.md', /id 'com.github.blindpirate.gogradle' version '(\w|\d|\.|\-)*'/, "id 'com.github.blindpirate.gogradle' version '${version}'")
        updateVersion('docs/getting-started.md', /id 'com.github.blindpirate.gogradle' version '(\w|\d|\.|\-)*'/, "id 'com.github.blindpirate.gogradle' version '${version}'")
        updateVersion('src/main/java/com/github/blindpirate/gogradle/GogradleGlobal.java', /GOGRADLE_VERSION = "(\w|\d|\.|\-)*"/, "GOGRADLE_VERSION = \"${version}\"")
        updateVersion('buildSrc/src/main/groovy/com/github/blindpirate/gogradle/TestTop1000Task.groovy', /gogradle-(\d|\.)*-all\.jar/, "gogradle-${version}-all.jar")
    }
}

pluginBundle {
    plugins {
        golangPlugin {
            website = 'https://github.com/blindpirate/gogradle'
            vcsUrl = 'https://github.com/blindpirate/gogradle'
            description = 'Full-featured Build Support for Golang'
            tags = ['go', 'golang', 'build', 'test']
            id = 'com.github.blindpirate.gogradle'
            displayName = 'Gogradle - Full-featured Build Plugin for Golang'
        }
    }
}

compileJava.dependsOn updateVersion

publishPlugins.dependsOn 'updateVersion', 'shadowJar'

/************** kotlin **************/
tasks.withType(KotlinCompile) {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

/************** shadow **************/

shadowJar {
    dependencies {
        exclude 'org/gradle/**', 'groovy/**', 'org/codehaus/groovy/**', 'META-INF/services/org.codehaus.groovy*'
    }
    archiveClassifier = 'all'
}

/************ spotbugs ****************/
spotbugs {
    excludeFilter = file("config/spotbugs/exclude.xml")
}

spotbugsMain {
    reports {
        xml.enabled = false
        html.enabled = true
    }
}


/************ codeNarc ****************/

codenarcTest {
    exclude "**/DependencyTreeNodeTest.groovy"
}
