/*
 * Copyright (c) 2008-2015 MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

apply plugin: 'eclipse'
apply plugin: 'idea'

def configDir = new File(rootDir, 'config')
ext.nettyVersion = '4.0.26.Final'

buildscript {
    repositories {
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
        jcenter()
        mavenCentral()
        mavenLocal()
    }
    dependencies {
        classpath 'org.kordamp.gradle:clirr-gradle-plugin:0.2.2'
        classpath 'com.netflix.nebula:gradle-extra-configurations-plugin:1.12.+'
        classpath 'com.bmuschko:gradle-nexus-plugin:2.2'
    }
}

//////////////////////////////////////////
// Common behavior                      //
//////////////////////////////////////////

configure(subprojects.findAll { it.name != 'util' }) {
    apply plugin: 'java'
    apply plugin: 'optional-base'

    evaluationDependsOn(':util')

    group = 'org.mongodb'
    version = '3.3.0'
    sourceCompatibility = JavaVersion.VERSION_1_6
    targetCompatibility = JavaVersion.VERSION_1_6

    repositories {
        mavenCentral()
        maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
        mavenLocal()
    }

    dependencies {
        compile 'org.slf4j:slf4j-api:1.7.6', optional
    }

    /* Compiling */
    tasks.withType(AbstractCompile) {
        options.encoding = 'ISO-8859-1'
        options.fork = true
        options.debug = true
        options.compilerArgs = ['-Xlint:all', '-Xlint:-options']

        onlyIf { JavaVersion.current().isJava7Compatible() }
    }

    project.ext.buildingWith = { propertyName ->
        project.hasProperty(propertyName) && project.property(propertyName).toBoolean()
    }

    javadoc {
        exclude "**/com/mongodb/**/internal/**"

        dependsOn project(':util').compileJava //We need taglets to be compiled
        options.author = true
        options.version = true
        options.links 'http://docs.oracle.com/javase/7/docs/api/'
        options.tagletPath project(':util').sourceSets.main.output.classesDir
        options.taglets 'ManualTaglet'
        options.taglets 'ServerReleaseTaglet'
        options.encoding = 'UTF-8'
        options.charSet 'UTF-8'
        options.docEncoding 'UTF-8'
        options.header = '''
            <script type="text/javascript">
            <!-- Set the location hash in the classFrame -->
            try {
              locationHash = top.location.hash;
              if (window.name == "classFrame" && locationHash != "") {
                window.location.hash = locationHash;
              }
            } catch (error) {}
            <!-- GA Tracking code -->
            if (window.name == "" || window.name == "classFrame") {
                var _elqQ = _elqQ || [];
                _elqQ.push(["elqSetSiteId", "413370795"]);
                _elqQ.push(["elqTrackPageView"]);
                (function () {
                function async_load() { var s = document.createElement("script"); s.type = "text/javascript"; s.async = true; s.src = "//img03.en25.com/i/elqCfg.min.js"; var x = document.getElementsByTagName("script")[0]; x.parentNode.insertBefore(s, x); }
                if (window.addEventListener) window.addEventListener("DOMContentLoaded", async_load, false);
                else if (window.attachEvent) window.attachEvent("onload", async_load);
                })();
            }
            </script>
        '''
    }
}

configure(subprojects.findAll { it.name != 'util' && it.name != 'mongo-java-driver' }) {
    apply plugin: 'checkstyle'
    apply plugin: 'findbugs'
    apply plugin: 'jacoco'
    apply plugin: 'groovy'
    apply plugin: 'codenarc'

    dependencies {
        testCompile 'org.codehaus.groovy:groovy-all:2.3.9'
        testCompile 'org.spockframework:spock-core:1.1-groovy-2.3-SNAPSHOT'
        testCompile 'cglib:cglib-nodep:2.2.2'
        testCompile 'org.objenesis:objenesis:1.3'
        testCompile 'org.hamcrest:hamcrest-all:1.3'
        testCompile 'ch.qos.logback:logback-classic:1.1.1'
        testCompile project(':util') //Adding categories to classpath
    }

    sourceSets {
        main {
            java.srcDirs = ['src/main']
        }
        test {
            groovy.srcDirs = ['src/test/functional', 'src/test/unit']
            java.srcDirs = ['src/test/functional', 'src/test/unit']
        }
    }

    /* Testing */
    tasks.withType(Test) {
        maxHeapSize = "3g"
        maxParallelForks = 1

        systemProperties(
                'org.mongodb.test.uri': System.getProperty('org.mongodb.test.uri', null),
                'org.mongodb.useSocket': System.getProperty('org.mongodb.useSocket', 'false'),
                'org.mongodb.disableAsync': System.getProperty('org.mongodb.disableAsync', 'false'),
                'org.mongodb.async.type': System.getProperty('org.mongodb.async.type', 'nio2'),

                'javax.net.ssl.trustStore': System.getProperty('javax.net.ssl.trustStore', "${System.getProperty('user.home')}/.keystore"),
                'javax.net.ssl.keyStore': System.getProperty('javax.net.ssl.keyStore', "${System.getProperty('user.home')}/.keystore"),
                'javax.net.ssl.keyStorePassword': System.getProperty('javax.net.ssl.keyStorePassword', 'changeit'),
                'javax.net.ssl.trustStorePassword': System.getProperty('javax.net.ssl.trustStorePassword', 'changeit')
        )

        if (project.buildingWith('ssl.enabled')) {
            systemProperties(
                    'javax.net.ssl.keyStoreType': project.property('ssl.keyStoreType'),
                    'javax.net.ssl.keyStore': project.property('ssl.keyStore'),
                    'javax.net.ssl.keyStorePassword': project.property('ssl.keyStorePassword'),
                    'javax.net.ssl.trustStoreType': project.property('ssl.trustStoreType'),
                    'javax.net.ssl.trustStore': project.property('ssl.trustStore'),
                    'javax.net.ssl.trustStorePassword': project.property('ssl.trustStorePassword')
            )
        }

        if (project.buildingWith('gssapi.enabled')) {
            systemProperties(
                    'sun.security.krb5.debug': project.getProperty('sun.security.krb5.debug'),
                    'javax.security.auth.useSubjectCredsOnly': "false",
                    'java.security.krb5.kdc': project.getProperty('krb5.kdc'),
                    'java.security.krb5.realm': project.getProperty('krb5.realm'),
                    'java.security.auth.login.config': project.getProperty('auth.login.config'),
                    )
        }

        useJUnit {
            if (!project.buildingWith('rs.enabled')) {
                excludeCategories 'category.ReplicaSet'
            }
            if (project.buildingWith('quicktest')) {
                excludeCategories 'category.SlowUnit'
            }
            if (project.buildingWith('travistest')) {
                excludeCategories 'category.SlowUnit', 'category.Slow'
            }
        }

        jacoco { enabled = false }

        beforeTest { descr ->
            logger.info("[Test ${descr.className} > ${descr.name}]")
        }

        afterTest { descr, result ->
                def failureStartTime = result.getResultType().toString() == "FAILURE" ? " Started at: ${result.getStartTime()}" : ""
                logger.info("[Test ${descr.className} > ${descr.name}] ${result.getResultType()} "
                        + "(${result.getEndTime() - result.getStartTime()} ms) ${failureStartTime}")

        }

        testLogging { exceptionFormat = 'full' }
    }

    task testSlowUnit(type: Test) {
        useJUnit {
            includeCategories 'category.SlowUnit'
        }
    }

    gradle.taskGraph.whenReady { taskGraph ->
        if (taskGraph.hasTask(testCoverage)) {
            tasks.withType(Test) { jacoco { enabled = true } }
        }
    }

    task testCoverage(dependsOn: test)

    /* Code quality */

    checkstyle {
        toolVersion = "6.2"
        configFile = new File(configDir, 'checkstyle.xml')
        configProperties.checkstyleConfigDir = configDir
    }

    findbugs {
        excludeFilter = new File(configDir, 'findbugs-exclude.xml')
        sourceSets = [sourceSets.main]
        toolVersion = '3.0.1'
    }

    codenarc {
        toolVersion = '0.24'
        reportFormat = project.buildingWith('xmlReports.enabled') ? 'xml' : 'html'
    }

    tasks.withType(FindBugs) {
        reports {
            xml.enabled = project.buildingWith('xmlReports.enabled')
            html.enabled = !project.buildingWith('xmlReports.enabled')
        }
    }
}

task docs(type: Javadoc) {
    source subprojects.grep({ it.name != 'util' }).collect {project -> project.sourceSets.main.allJava }
    options = subprojects.first().javadoc.options
    dependsOn = subprojects.first().javadoc.dependsOn
    excludes =  subprojects.first().javadoc.excludes
    classpath = files(subprojects.collect {project -> project.sourceSets.main.compileClasspath})
    destinationDir = new File(projectDir, 'build/docs')
}

//////////////////////////////////////////
// Root project configuration           //
//////////////////////////////////////////
task wrapper(type: Wrapper) {
    gradleVersion = '2.4'
}

gradle.buildFinished { BuildResult result ->
    if (result.failure && !JavaVersion.current().isJava7Compatible()) {
        gradle.rootProject.logger.error("\n* Warning:\nJDK ${JavaVersion.VERSION_1_7} is minimal requirement for building the driver. " +
                                        "You have ${JavaVersion.current()}.")
    }
}

apply from: 'gradle/deploy.gradle'

