import java.util.jar.Attributes

apply plugin: 'groovy'

archivesBaseName = "gradle-${name.replaceAll("\\p{Upper}") { "-${it.toLowerCase()}" } }"

if (!sourceSets.main.groovy.srcDirs.any{ it.exists() }) {
    // Remove configurations.groovy from compile and runtime classpaths.
    configurations {
        compile.extendsFrom = []
    }
}

dependencies {
    testCompile libraries.junit, libraries.jmock, libraries.spock
}

apply from: "$rootDir/gradle/compile.gradle"

test {
    maxParallelForks = guessMaxForks()
}

tasks.matching { it instanceof Compile || it instanceof GroovyCompile }.all {
    options.compilerArgs << "-Xlint:unchecked"
}

tasks.withType(Jar).each { jar ->
    jar.manifest.mainAttributes([
            (Attributes.Name.IMPLEMENTATION_TITLE.toString()): 'Gradle',
            (Attributes.Name.IMPLEMENTATION_VERSION.toString()): version,
    ])
}

generatedResourcesDir = file("$buildDir/generated-resources/main")

task classpathManifest(type: ClasspathManifest)
sourceSets.main.output.dir generatedResourcesDir, buildBy: classpathManifest

if (file("src/testFixtures").exists()) {
    apply from: "$rootDir/gradle/testFixtures.gradle"
}

if (file("src/integTest").exists()) {
    apply from: "$rootDir/gradle/integTest.gradle"
}

class ClasspathManifest extends DefaultTask {
    @OutputFile
    File getManifestFile() {
        return new File(project.generatedResourcesDir, "${project.archivesBaseName}-classpath.properties")
    }

    @Input
    Properties getProperties() {
        def properties = new Properties()
        properties.runtime = project.configurations.runtime.fileCollection { it instanceof ExternalDependency }.collect {it.name}.join(',')
        properties.projects = project.configurations.runtime.allDependencies.withType(ProjectDependency).collect {it.dependencyProject.archivesBaseName}.join(',')
        return properties
    }

    @TaskAction
    def generate() {
        manifestFile.withOutputStream { properties.save(it, 'module definition') }
    }
}