/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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.
 */
import org.gradle.api.internal.artifacts.publish.DefaultPublishArtifact

ext.artifactoryUser = project.hasProperty('artifactoryUser') ? project.artifactoryUser : System.getenv('ARTIFACTORY_USER')
ext.artifactoryPassword = project.hasProperty('artifactoryPassword') ? project.artifactoryPassword : System.getenv('ARTIFACTORY_PASSWORD')

if (!artifactoryUser) {
    // try to read artifactory.properties
    def base = file(projectDir)
    def artifactoryFile = new File(base, 'artifactory.properties')
    while (!artifactoryFile.exists()) {
        base = base.parentFile
        if (!base) break
        artifactoryFile = new File(base, 'artifactory.properties')
    }
    if (artifactoryFile.exists()) {
        logger.lifecycle 'Found artifactory.properties in ' + base.path
        def props = new Properties()
        props.load(artifactoryFile.newReader())
        ext.artifactoryUser = props.getProperty('artifactoryUser','')
        ext.artifactoryPassword = props.getProperty('artifactoryPassword','')
    } else {
        logger.lifecycle 'No artifactory.properties file found'
    }
}

logger.lifecycle "ArtifactoryUser user: $artifactoryUser"

allprojects {
    if (project == rootProject || rootProject.ext.modules().contains(project)) {
        apply plugin: 'com.jfrog.artifactory-upload'

        artifactory {
            contextUrl = project.hasProperty('artifactoryContext') ? project.artifactoryContext : 'https://oss.jfrog.org'
            resolve {
                repository {
                    repoKey = 'libs-release'
                }
            }
            publish {
                excludePatterns = [
//                        'org/codehaus/groovy/groovy/**',
//                        'org/codehaus/groovy/groovy-ant/**',
//                        'org/codehaus/groovy/groovy-backports-compat23/**',
//                        'org/codehaus/groovy/groovy-binary/**',
//                        'org/codehaus/groovy/groovy-bsf/**',
//                        'org/codehaus/groovy/groovy-console/**',
//                        'org/codehaus/groovy/groovy-docgenerator/**',
//                        'org/codehaus/groovy/groovy-groovydoc/**',
//                        'org/codehaus/groovy/groovy-groovysh/**',
//                        'org/codehaus/groovy/groovy-jmx/**',
//                        'org/codehaus/groovy/groovy-json/**',
//                        'org/codehaus/groovy/groovy-jsr223/**',
//                        'org/codehaus/groovy/groovy-macro/**',
//                        'org/codehaus/groovy/groovy-nio/**',
//                        'org/codehaus/groovy/groovy-servlet/**',
//                        'org/codehaus/groovy/groovy-sql/**',
//                        'org/codehaus/groovy/groovy-swing/**',
//                        'org/codehaus/groovy/groovy-templates/**',
//                        'org/codehaus/groovy/groovy-test/**',
//                        'org/codehaus/groovy/groovy-testng/**',
//                        'org/codehaus/groovy/groovy-xml/**',
                        'org/codehaus/groovy/groovy/*/groovy-all-*',
                        'org/codehaus/groovy/groovy/*/groovy-bom-*',
                        'org/codehaus/groovy/groovy/*/groovy-backports-*',
                        'org/codehaus/groovy/groovy/*/groovy-binary-*'
                ].join(',')
                repository {
                    repoKey = project.hasProperty('artifactoryRepoKey') ? project.artifactoryRepoKey : 'oss-snapshot-local'
                    //The Artifactory repository key to publish to
                    //when using oss.jfrog.org the credentials are from Bintray. For local build we expect them to be found in
                    //~/.gradle/gradle.properties, otherwise to be set in the build server
                    username = rootProject.artifactoryUser
                    password = rootProject.artifactoryPassword
                }
            }
        }
    }
}

artifactoryPublish {
    def curDate = new Date()
    def pomSource = { a -> "$projectDir/target/poms/pom-${a.name - 'groovy-'}.xml" }
    def destBase = { a -> "org/codehaus/groovy/${a.name}/${version}/${a.name}-${version}${a.classifier ? '-' + a.classifier : ''}" }
    def newDetails = { orig, newFile, newExt, newType -> gradleDeployDetails(new DefaultPublishArtifact(
            orig.name, newExt, newType, orig.classifier, curDate, newFile), 'artifacts', destBase(orig) + '.' + newExt) }
    def makeTransformedDetails = { orig -> newDetails(orig, orig.file, orig.extension, orig.extension) }
    def makeTransformedPomDetails = { orig -> newDetails(orig, file(pomSource(orig)), 'pom', 'pom') }
    def makeTransformedPomSigDetails = { orig -> newDetails(orig, file(pomSource(orig) + '.asc'), 'pom.asc', 'asc') }
    mavenDescriptor = new File("$projectDir/target/poms/pom-groovy.xml")
    doFirst{
        configurations.archives.artifacts.findAll{ it.name != project.name }.each {
            // the plugin we are using uses the project name rather than the artifact name
            // as the artifactId, so we add the transformed one ourselves
            // this also covers signatures which we already added during install
            deployDetails.add(makeTransformedDetails(it))
            if (!it.classifier && (it.type == 'jar' || it.type == 'zip')) {
                // add the pom and its signature
                deployDetails.add(makeTransformedPomDetails(it))
                if (isReleaseVersion) {
                    deployDetails.add(makeTransformedPomSigDetails(it))
                }
            }
        }
        deployDetails.add(makeTransformedPomDetails(name: 'groovy-all'))
        deployDetails.add(makeTransformedPomDetails(name: 'groovy-bom'))

        if (isReleaseVersion) {
            deployDetails.add(makeTransformedPomSigDetails(name: 'groovy-all'))
            deployDetails.add(makeTransformedPomSigDetails(name: 'groovy-bom'))
            allprojects {
                if (project == rootProject || rootProject.ext.modules().contains(project)) {
                    configurations.archives.artifacts.findAll {
                        it.name == project.name && it.type == 'jar' && it.extension == 'jar' && !it.classifier
                    }.each {
                        // add pom signatures
                        def pomSigLocation = "$project.projectDir/target/poms/pom-${project == rootProject ? 'groovy' : 'default'}.xml.asc"
                        deployDetails.add(newDetails(it, file(pomSigLocation), 'pom.asc', 'pom'))
                    }
                }
            }
        }
    }
}

artifactoryPublish.dependsOn(['backportJars', 'install'])
