import groovy.xml.NamespaceBuilder

configurations {
    deployerJars
}

dependencies {
    deployerJars "org.apache.maven.wagon:wagon-webdav:1.0-beta-2",
				 "org.apache.maven:maven-ant-tasks:2.1.0"

}


def artifact = NamespaceBuilder.newInstance(ant, 'antlib:org.apache.maven.artifact.ant')

task generatePoms(type: Copy) {
    pomsDir = "$buildDir/poms"
    from('maven') {
        include '*.pom.in'
        filter(org.apache.tools.ant.filters.ReplaceTokens, tokens: ['grails.version': version])
        rename '(.*)\\.in', '$1'
    }
    into pomsDir
}

task mavenInstall(dependsOn: [generatePoms, tasks.withType(Jar).all]) << {
    tasks.withType(Jar).matching({task -> task.mavenArtifact } as Spec).each {jar ->
        artifact.install(file: jar.archivePath) {
            pom(file: "$generatePoms.pomsDir/$jar.baseName${jar.appendix ? '-' + jar.appendix : ""}.pom")
        }
    }
    
    // install the grails parent POM
    artifact.install(file: "${libs.destinationDir}/grails-${version}.jar") {
    	pom(file: "$generatePoms.pomsDir/grails.pom")
    }
}

task mavenDeploy(dependsOn: [generatePoms, tasks.withType(Jar).all]) << {
	def antBuilderClasspath = services.get(org.gradle.api.internal.ClassPathRegistry).getClassPathFiles('ANT') +
	services.get(org.gradle.api.internal.ClassPathRegistry).getClassPathFiles('LOCAL_GROOVY') + 
	configurations.deployerJars.files
	def isolatedAnt = services.get(org.gradle.api.internal.project.IsolatedAntBuilder)
	
    tasks.withType(Jar).matching({task -> task.mavenArtifact } as Spec).each {jar ->
        isolatedAnt.execute(antBuilderClasspath) {
            'antlib:org.apache.maven.artifact.ant:deploy'(file: jar.archivePath) {
                pom(file: "$generatePoms.pomsDir/$jar.baseName${jar.appendix ? '-' + jar.appendix : ""}.pom")
            }
        }
    }
    // deploy the grails parent POM
	isolatedAnt.execute(antBuilderClasspath) {
	'antlib:org.apache.maven.artifact.ant:deploy'(file: "${libs.destinationDir}/grails-${version}.jar") {
		pom(file:"$generatePoms.pomsDir/grails.pom")
	 }
   }
}
