buildscript {
    repositories {
        mavenLocal()
        jcenter()
        gradlePluginPortal() //for sonarqube plugin
    }
    dependencies {
        classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.12.RELEASE'
        classpath 'pl.allegro.tech.build:axion-release-plugin:1.7.2'
        classpath 'com.toomuchcoding:uptodate-gradle-plugin:+'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:+'
        if (project.hasProperty("coverage")) {
            classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:+'
            classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.5'
        }
    }
}

apply from: "gradle/version.gradle"

scmVersion {
    tag {
        prefix = 'release'
        versionSeparator = '/'
    }
}

allprojects {
    group = 'com.ofg'
    project.version = scmVersion.version
}

Set emptySubprojects = [project(':micro-deps-root'), project(':stub-runner-root')]
Set srcSubprojects = subprojects - emptySubprojects

configure(srcSubprojects) {
    apply plugin: 'groovy'
    apply from: "${rootProject.projectDir}/gradle/publish.gradle"

    bintray {
        pkg {
            repo = project.name.startsWith("micro-deps") ? 'micro-deps' : 'micro'
            vcsUrl = 'https://github.com/4finance/micro-infra-spring.git'
        }
    }
}

apply from: "gradle/release.gradle"

//NOTE: All release and publishing modifications (including further scmVersion closure) should be put AFTER the apply of publish.gradle and/or release.gradle
//      (to be not overridden by the default values applied in those files)


allprojects {
    repositories {
        mavenLocal()
        mavenCentral()
        jcenter()
    }

    configurations {
        all {
            resolutionStrategy {
                exclude group: 'log4j', module: 'log4j'
                force 'org.apache.httpcomponents:httpclient:4.5.2'
                force 'org.jboss.logging:jboss-logging:3.3.0.Final'

                eachDependency { DependencyResolveDetails details ->
                    if (details.requested.group == 'org.slf4j') { details.useVersion '1.7.21' }
                    if (details.requested.group == 'com.fasterxml.jackson.core') { details.useVersion '2.6.7' }

                    // To prevent an accidental usage of groovy-all.jar and groovy.jar in different versions
                    // all modularized Groovy jars are replaced with groovy-all.jar by default.
                    if (details.requested.group == 'org.codehaus.groovy' && details.requested.name != 'groovy-all') {
                        details.useTarget("org.codehaus.groovy:groovy-all:${details.requested.version}")
                    }
                }
            }
        }
    }
}

task addHashFile { 
    doLast {
        String gitCmd = "git log --pretty=format:'%H' -n 1"
        def proc = gitCmd.execute()
        proc.waitFor()
        project.buildDir.mkdirs()
        new File(project.buildDir, "commitHash.txt").withWriter { it << proc.in.text }
    }
}

configure(emptySubprojects + rootProject) {
    apply plugin: 'base'
}

configure(srcSubprojects) {

    apply plugin: 'com.toomuchcoding.uptodate'
    apply plugin: "io.spring.dependency-management"

    sourceCompatibility = 1.8

    dependencyManagement {
        imports {
            mavenBom 'org.springframework.cloud:spring-cloud-starter-parent:Edgware.SR3'
        }

        dependencies {
            dependency 'org.codehaus.groovy:groovy-all:2.4.15'
            dependency 'com.google.guava:guava:20.0'
            dependency 'commons-io:commons-io:2.6'

            dependencySet(group: 'org.apache.curator', version: '2.11.1') {
                entry 'curator-x-discovery'
                entry 'curator-test'
            }
            dependencySet(group: 'org.aspectj', version: '1.9.0') {
                entry 'aspectjrt'
                entry 'aspectjweaver'
            }
            dependencySet(group: 'io.dropwizard.metrics', version: '4.0.2') {
                entry 'metrics-core'
                entry 'metrics-jvm'
                entry 'metrics-jmx'
                entry 'metrics-graphite'
            }

            //test
            dependency 'io.rest-assured:rest-assured:3.0.7'
            dependency 'com.github.tomakehurst:wiremock-standalone:2.16.0'
            dependency 'cglib:cglib-nodep:3.2.6'
            dependency 'org.objenesis:objenesis:2.6'
            dependency 'com.github.stefanbirkner:system-rules:1.17.1'

            dependencySet(group: 'ch.qos.logback', version: '1.2.3') {
                entry 'logback-core'
                entry 'logback-classic'
            }
            dependencySet(group: 'org.spockframework', version: '1.1-groovy-2.4') {
                entry 'spock-core'
                entry 'spock-spring'
            }
            dependency 'info.solidsoft.spock:spock-global-unroll:0.5.1'
            dependencySet(group: 'org.awaitility', version: '3.1.0') {
                entry 'awaitility'
                entry 'awaitility-groovy'
            }
            dependencySet(group: 'com.jayway.jsonpath', version: '2.4.0') {
                entry 'json-path'
                entry 'json-path-assert'
            }
        }
    }

    test {
        jvmArgs project.gradle.startParameter.systemPropertiesArgs.entrySet().collect{"-D${it.key}=${it.value}"}
        jvmArgs '-Xmx512m'
        testLogging {
            exceptionFormat = 'full'
        }
        maxHeapSize = "2g"
        maxParallelForks = project.hasProperty('parallel') ? Runtime.runtime.availableProcessors() : 1
    }

    jar {
        dependsOn addHashFile
        from new File(project.buildDir, "commitHash.txt")
    }

    //Dependencies in all subprojects - http://solidsoft.wordpress.com/2014/11/13/gradle-tricks-display-dependencies-for-all-subprojects-in-multi-project-build/
    task allDeps(type: DependencyReportTask) {}
    task allInsight(type: DependencyInsightReportTask) {}

    configurations {
        jansi.extendsFrom(runtime)
    }
    groovydoc {
        def title = "IPDS ${version}"
        groovyClasspath = project.configurations.jansi
    }
    dependencies {
        jansi 'org.fusesource.jansi:jansi:1.17'
    }
}

if (project.hasProperty("coverage")) {
    configure(srcSubprojects + rootProject) {
        apply plugin: 'jacoco'
    }

    apply plugin: 'com.github.kt3k.coveralls'
    apply plugin: 'org.sonarqube'

    sonarqube {
        properties {
            property "sonar.projectName", "micro-infra-spring"
        }
    }

    configure(srcSubprojects) {
        jacocoTestReport {
            reports {
                xml.enabled = true // coveralls plugin depends on xml format report
            }
        }

        test {
            jacoco {
                excludes = ['*Configuration']
            }
        }

        sonarqube {
            properties {
                property "sonar.groovy.jacoco.reportPath", "$buildDir/jacoco/test.exec"     //TODO: Could be taken from JaCoCo extension directly
            }
        }
    }

    coveralls {
        sourceDirs = files(srcSubprojects.sourceSets.main.allSource.srcDirs).files.absolutePath
    }

    task jacocoRootReport(type: JacocoReport) {
        // Gather execution data from all subprojects
        // (change this if you e.g. want to calculate unit test/integration test coverage separately)
        executionData fileTree(project.rootDir.absolutePath).include("**/build/jacoco/*.exec")

        // Add all relevant sourcesets from the subprojects
        srcSubprojects.each {
            sourceSets it.sourceSets.main
        }

        reports {
            xml.enabled true
            xml.destination file("${buildDir}/reports/jacoco/test/jacocoTestReport.xml")
        }
    }

    // always run the tests before generating the report
    jacocoRootReport.dependsOn {
        srcSubprojects*.test
        srcSubprojects*.jacocoTestReport
    }
}

//Individual HTML test reports could be disabled to speed up build a little bit if testReport was the only one used - http://stackoverflow.com/a/16921750
task testReport(type: TestReport) {
    destinationDir = file("$buildDir/reports/allTests")
    reportOn srcSubprojects*.test
}

