/*
 * 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.
 */



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

task javadocJar(type: Jar) {
  from {
    javadoc
  }
  classifier = 'javadoc'
}

publishing {
  publications {
    maven(MavenPublication) {
      pom {
        withXml {
          // This black magic checks to see if a dependency has the flag ext.optional=true
          // set on it, and if so marks the dependency as optional in the maven pom
           def depMap = [:]
          ['api','implementation','compileOnly','runtimeOnly'].each { cfgName ->
            def cfg = project.configurations.findByName(cfgName)
            if (cfg) {
              cfg.dependencies.each { depMap[it.name] = it }
            }
          }
          def runtimeClasspathCfg = project.configurations.findByName('runtimeClasspath')
          runtimeClasspathCfg?.allDependencies?.each { depMap[it.name] = it }

          def runtimeOnlyDeps = project.configurations.runtimeOnly.dependencies.collectEntries {
            [it.name, it]
          }
          depMap.putAll(runtimeOnlyDeps)
          def implementationDependencies = project.configurations.implementation.dependencies.collectEntries {
            [it.name, it]
          }
          depMap.putAll(implementationDependencies)
          def apiDependencies = project.configurations.api.dependencies.collectEntries {
            [it.name, it]
          }
          depMap.putAll(apiDependencies)
          asNode().dependencies.dependency.findAll {
            def dep = depMap.get(it.artifactId.text())
            return dep?.hasProperty('optional') && dep.optional
          }.each {
            if (it.optional) {
              it.optional.value = 'true'
            } else {
              it.appendNode('optional', 'true')
            }
          }
        }
      }
    }
  }
}