/*
 * Copyright 2011 LMAX Ltd.
 *
 * 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: 'java'
apply plugin: 'osgi'
apply plugin: 'maven'
apply plugin: 'signing'
apply plugin: 'eclipse'   // Only used so the Eclipse STS Gradle plugin can see the 'perf' source set dependencies. :-(
apply plugin: 'checkstyle'

defaultTasks 'build'

group = 'com.lmax'
version = new Version(major: 3, minor: 2, revision: 0)

ext {
    fullName = 'Disruptor Framework'
    fullDescription = 'Disruptor - Concurrent Programming Framework'
    teamName = 'LMAX Disruptor Development Team'
    siteUrl = 'http://lmax-exchange.github.com/disruptor'
    sourceUrl = 'git@github.com:LMAX-Exchange/disruptor.git'

    javaCompilerExecutable = System.env['JAVA_HOME'] ? System.env['JAVA_HOME'] + '/bin/javac' : 'javac'

    if (!project.hasProperty('sonatypeUrl')) sonatypeUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2'
    if (!project.hasProperty('sonatypeUsername')) sonatypeUsername = ''
    if (!project.hasProperty('sonatypePassword')) sonatypePassword = ''
}

sourceSets {
    perf.java.srcDir 'src/perftest/java'
}

eclipse.classpath.plusConfigurations += sourceSets.perf.compileClasspath

repositories {
    mavenCentral()
}

dependencies {
    testCompile 'junit:junit:4.5', 'org.jmock:jmock-junit4:2.5.1', 'org.jmock:jmock-legacy:2.5.1', files('lib/test/hdrhistogram-1.0-SNAPSHOT.jar')
    perfCompile 'com.google.caliper:caliper:0.5-rc1', 'junit:junit:4.5', files('lib/test/hdrhistogram-1.0-SNAPSHOT.jar')
}

sourceCompatibility = 1.6
targetCompatibility = 1.6

tasks.withType(Compile) {
    options.compilerArgs << '-XDignore.symbol.file' << '-Xlint:unchecked'
    options.debug = true
    options.fork = true
    options.forkOptions.executable = javaCompilerExecutable
    options.warnings = false
}

compilePerfJava {
    classpath += sourceSets.main.runtimeClasspath
}

def perfTests = [Test: '**/*', Throughput: '**/*ThroughputTest.class', ThroughputMultiThreaded: '**/Three*ThroughputTest.class', Latency: '**/*LatencyTest.class']

def createPerfTest = { type, pattern ->
    task("perf$type", type: Test, dependsOn: ['classes', 'perfClasses'], group: 'Performance test') {
        outputs.upToDateWhen { false }    // always run perf tests, even if no inputs have changed
        testClassesDir = sourceSets.perf.output.classesDir
        classpath = sourceSets.perf.runtimeClasspath + sourceSets.main.runtimeClasspath
        include pattern
        testLogging.showStandardStreams = true
    }
}

perfTests.each(createPerfTest)

tasks.addRule('Pattern: perfTestSingle<ClassName>') { taskName ->
    if (taskName.startsWith('perfTestSingle')) {
        def type = taskName - 'perf'
        def pattern = "**/${taskName - 'perfTestSingle'}.class"
        createPerfTest(type, pattern)
    }
}

javadoc {
    title = '<h1>Disruptor</h1>'

    options.addStringOption('XDignore.symbol.file', '-quiet')
    options.author = true
    options.bottom = "<i>Copyright &#169; 2011 - ${Calendar.instance[Calendar.YEAR]} LMAX Ltd. All Rights Reserved.</i>"
    options.use = true
    options.version = true
    options.windowTitle = 'Disruptor API'
}

jar {
    manifest.attributes('Built-By': System.properties['user.name'],
                        'Bundle-Name': fullName,
                        'Bundle-Vendor': teamName,
                        'Bundle-Description': fullDescription,
                        'Bundle-DocURL': siteUrl)
}

task sourcesJar(type: Jar) {
    classifier = 'sources'
    from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

artifacts {
    archives sourcesJar, javadocJar
}

def projectPom = {
    name = fullName
    description = fullDescription
    url = siteUrl

    scm {
        url = "scm:$sourceUrl"
        connection = "scm:$sourceUrl"
    }

    licenses {
        license {
            name = 'The Apache Software License, Version 2.0'
            url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
            distribution = 'repo'
        }
    }

    developers {
        developer {
            id = 'team'
            name = teamName
            email = 'lmax-disruptor@googlegroups.com'
        }
    }
}

install {
    repositories.mavenInstaller.pom.project(projectPom)
}

signing {
    required { gradle.taskGraph.hasTask('uploadArchives') }
    sign configurations.archives
}

uploadArchives {
    repositories.mavenDeployer {
        beforeDeployment { deployment -> signing.signPom(deployment) }

        repository(url: sonatypeUrl) {
            authentication(userName: sonatypeUsername, password: sonatypePassword)
        }

        pom.project(projectPom)
    }
}

build.dependsOn perfClasses

task listJars << {
    configurations.perfCompile.each { file -> println file.name }
}

task tempLibs(type: Sync) {
    from configurations.perfCompile
    into('templib')
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.5'
}

class Version {
    int major, minor = 0, revision = 0
    boolean snapshot
    String stage

    String toString() {
        "$major.$minor.$revision${stage ? '.' + stage : ''}${snapshot ? '-SNAPSHOT' : ''}"
    }
}
