import org.apache.tools.ant.filters.ReplaceTokens

apply plugin: 'java-library'
apply plugin: 'maven-publish'
apply plugin: 'signing'
apply plugin: 'eclipse'


buildscript {
    dependencies {
        classpath group: 'com.liferay', name: 'com.liferay.gradle.plugins.tlddoc.builder', version: '2.0.1'
        classpath("io.github.gradle-nexus.publish-plugin:io.github.gradle-nexus.publish-plugin.gradle.plugin:2.0.0")
    }
    repositories {
        mavenLocal()
        mavenCentral()
        gradlePluginPortal()
    }
}
apply plugin: 'com.liferay.tlddoc.builder'
apply plugin: 'io.github.gradle-nexus.publish-plugin'
group = "org.opencms"

buildDir = build_directory

java {
    sourceCompatibility = JavaVersion.toVersion(java_target_version)
    targetCompatibility = JavaVersion.toVersion(java_target_version)
}
signing {
    useGpgCmd()
}

nexusPublishing {
    repositories {
        sonatype {
            nexusUrl.set(uri("https://ossrh-staging-api.central.sonatype.com/service/local/"))
            snapshotRepositoryUrl.set(uri("https://central.sonatype.com/repository/maven-snapshots/"))
        }
    }
}



// use the same properties file as the OpenCms core does for the version information
// please note that in a Jenkins CI build, this properties file should be dynamically generated
def externalVersionProps = file("${buildDir}/../version.properties");
def propFile;
if (externalVersionProps.exists()){
    println "Using external version properties file: $externalVersionProps"
    propFile=externalVersionProps
}else{
    println 'Using internal version properties file'
    propFile=file("$projectDir/src/org/opencms/main/version.properties")
}

Properties vprops = new Properties()
vprops.load(new FileInputStream(propFile))
if (opencms_version) {
    version = opencms_version
}else{
    version = vprops['version.number']
}

// flag, indicating if javadoc should be skipped
boolean addJavadoc = !(project.hasProperty('skip_javadoc') && skip_javadoc.toBoolean())

// alternative variable name for the case where the version variable is used for something else, e.g. javadoc
ext.ocmsVersion = vprops['version.number']

// deal with external modules project
def extModulesProject = findProject(':extmodules')
def hasExtModules = null != extModulesProject
if (hasExtModules) {
    println 'Adding coreproject property to subprojects.'
    subprojects {
        ext.coreproject = ':'
    }
}

repositories {
    mavenLocal()
    if (project.hasProperty('additional_repositories')){
        additional_repositories.split(';').each{ repo ->
            maven { url repo }
        }
    }
    mavenCentral()
    maven {
        url 'https://maven.restlet.talend.com'
    }
    maven {
        url 'https://maven.vaadin.com/vaadin-addons'
    }
}

if (!project.hasProperty('max_heap_size')){
    project.ext.max_heap_size='1024m'
}

project.ext.allModuleNames = modules_list.split(',')
project.ext.modulesDistsDir = file("${project.buildDir}/modulesZip")


sourceSets{
    main {
        java.srcDirs=['src']
        resources.srcDirs=['src']
    }
    modules {
        java.srcDirs=['src-modules']
        resources.srcDirs=['src-modules']
    }
    gwt {
        java {
            srcDirs=['src-gwt']
            exclude '**/super_src/**'
        }
        resources {
            srcDirs=['src-gwt']
            exclude '**/super_src/**'
        }
    }
    setup {
        java.srcDirs=['src-setup']
        resources.srcDirs=['src-setup']
    }
    test {
        java {
            srcDirs=['test']
            exclude 'data/**'
        }
        resources {
            srcDirs=['test']
            exclude 'data/**'
        }
    }
    testGwt {
        java {
            srcDirs=['test-gwt']
            exclude '**/super_src/**'
        }
        resources {
            srcDirs=['test-gwt']
            exclude '**/super_src/**'
        }
    }
}

configurations {

    distribution {
        description = 'libraries included into the opencms distribution'
    }

    api {
        extendsFrom distribution
    }
    
    usedApis {
    	description = "APIs that should normally be provided by the servlet container, but are also needed for the CmsShell, so they're bundled in the WAR." 
    }

    compile {
        description = 'used to compile the opencms.jar and the modules jars'
        extendsFrom distribution
        extendsFrom usedApis
    }
    // Default configuration of the java-library plugin
    // It corresponds to our compile configuration, that's why we have to use extendsFrom here
    implementation {
        extendsFrom compile
    }

    modulesCompile {
        description = 'used to compile the modules classes'
        extendsFrom compile
    }

    // Default configuration of the java-library plugin
    // It corresponds to our compile configuration, that's why we have to use extendsFrom here
    modulesImplementation {
        extendsFrom modulesCompile
    }

    moduleDeps {
        description = 'additional dependencies required by external modules'
    }

    testCompile{
        extendsFrom modulesCompile
    }

    // Default configuration of the java-library plugin
    // It corresponds to our compile configuration, that's why we have to use extendsFrom here
    testImplementation {
        extendsFrom testCompile
    }

    gwtCompile {
        description = 'needed to generate the GWT JavaScript resources'
        extendsFrom modulesCompile
    }

    // Default configuration of the java-library plugin
    // It corresponds to our compile configuration, that's why we have to use extendsFrom here
    gwtImplementation {
        extendsFrom gwtCompile
    }

    testGwtCompile{
        description = 'needed to run GWT test cases'
        extendsFrom gwtCompile
    }

    // Default configuration of the java-library plugin
    // It corresponds to our compile configuration, that's why we have to use extendsFrom here
    testGwtImplementation {
        extendsFrom testGwtCompile
    }

    // Fix the jetty incompatibility for the version from distribution used by Solr and the one for the GWT test cases.
    testGwtRuntimeClasspath{
        resolutionStrategy {
            force 'org.eclipse.jetty:jetty-client:9.4.50.v20221201'
            force 'org.eclipse.jetty:jetty-http:9.4.50.v20221201'
            force 'org.eclipse.jetty:jetty-io:9.4.50.v20221201'
            force 'org.eclipse.jetty:jetty-util:9.4.50.v20221201'
            force 'org.eclipse.jetty.http2:http2-common:9.4.50.v20221201'
            force 'org.eclipse.jetty.http2:http2-client:9.4.50.v20221201'
            force 'org.eclipse.jetty.http2:http2-http-client-transport:9.4.50.v20221201'
        }
    }

    setupCompile {
        extendsFrom modulesCompile
    }

    // Default configuration of the java-library plugin
    // It corresponds to our compile configuration, that's why we have to use extendsFrom here
    setupImplementation {
        extendsFrom setupCompile
    }
}

// import dependencies
apply from: 'dependencies.gradle'
if (project.hasProperty('external_directories')){
    dependencies{
        moduleDeps fileTree(dir: external_directories).matching { include '**/lib/*.jar' }
        moduleDeps fileTree(dir: external_directories).matching { include '**/libext/*.jar' }
    }
}

eclipse.classpath.file {
    whenMerged { classpath ->
        classpath.entries.each {entry ->
            if ((entry.kind == 'src') && (entry.path.contains('gwt'))){
                entry.entryAttributes['test'] = 'true'
            }
            if (entry.kind == 'src' && entry.path == 'src') {
                entry.output='bin/main'
                entry.entryAttributes['test'] = 'false'
            }
        }
    }
}

eclipse.classpath.plusConfigurations = configurations.findAll { it.name.endsWith('Compile') }

eclipse.classpath.downloadSources=true

wrapper {
    gradleVersion = '7.5.1'
}

task copyDeps(type: Copy) {
    from configurations.distribution
    into "${buildDir}/deps"
}

task copyCompileDeps(type: Copy) {
    from configurations.compile
    into "${buildDir}/deps"
}

// Task from the java plugin
jar {
    manifest {
        attributes 'Implementation-Title': 'Alkacon OpenCms',
        'Implementation-Version': archiveVersion,
        'Build-Time': new java.util.Date().format("yyyy-MM-dd HH:mm:ss"),
        'OpenCms-Localization': 'en'
    }
    archiveBaseName = 'opencms-core'
    archiveFileName = 'opencms.jar'
    group 'OpenCms core JARs'

    include 'org/opencms/**'
    include 'org/vaadin/risto/**'
    include 'com/**'
    include 'META-INF/**'
    exclude '**/package.html'
    exclude '**/overview.html'
    exclude '**/.gitignore'

    if (externalVersionProps.exists()){
        exclude 'org/opencms/main/version.properties'
        from ("${buildDir}/.."){
            include 'version.properties'
            into 'org/opencms/main'
        }
    }

    metaInf {
        from("${projectDir}/webapp/WEB-INF/opencms.tld")
    }

    doLast {
        if (project.hasProperty('tomcat_update_target') && file(tomcat_update_target).exists()){
            println "copying ${project.buildDir}/libs/${archiveName} to ${tomcat_update_target}"
            copy {
                from  "${project.buildDir}/libs/${archiveName}"
                into tomcat_update_target
            }
        }
    }
}

// Task from the java plugin
javadoc {
    classpath += sourceSets.gwt.compileClasspath
    doLast {
        copy {
            from  "${projectDir}/doc/javadoc/logos"
            into "${buildDir}/docs/javadoc/logos"
        }
    }

    project.configure(options) {
        memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED
        charSet = "UTF-8"
        author="true"
        version="true"
        source= java_target_version
        linkSource="false"
        overview="${sourceSets.main.output.resourcesDir}/org/opencms/main/overview.html"
        docTitle="OpenCms Core API, version $ocmsVersion"
        windowTitle="OpenCms Core API, version $ocmsVersion"
        header = "<script type=\"text/javascript\"> if (window.location.href.indexOf(\"overview-frame\") == -1) { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.alkacon.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/Alkacon.svg\\\" /></a>\"); } else { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.opencms.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/OpenCms.svg\\\" /></a>\"); }</script>"
        use="true"
    }
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    archiveClassifier = 'javadoc'
    from "${buildDir}/docs/javadoc"
    archiveBaseName = 'opencms-core'
}

task sourcesJar(type: Jar) {
    from sourceSets.main.java.srcDirs
    archiveClassifier = 'sources'
    archiveBaseName = 'opencms-core'
}

task gwtJar(dependsOn: jar, type: Jar) {
    from sourceSets.gwt.output
    from (sourceSets.gwt.java.srcDirs){ include '**/*.java' }
    from (sourceSets.main.java.srcDirs){
        include '**/shared/**'
        include '**/gwt/CmsRpcException.java'
        include '**/ade/detailpage/CmsDetailPageInfo.java'
        include '**/db/CmsResourceState.java'
        include '**/jsp/CmsContainerJsonKeys.java'
        include '**/util/CmsPair.java'
        include '**/util/CmsDefaultSet.java'
        include '**/xml/content/CmsXmlContentProperty.java'
        include '**/workplace/editors/CmsTinyMceToolbarHelper.java'
    }
    includeEmptyDirs false
    archiveFileName = 'opencms-gwt.jar'
    archiveBaseName = 'opencms-gwt'
    exclude '**/.gitignore'
}

task modulesJar(type: Jar) {
    from sourceSets.modules.output
    archiveFileName = 'opencms-modules.jar'
    archiveBaseName = 'opencms-modules'
    group 'OpenCms core JARs'
    exclude '**/.gitignore'
}

task javadocModules(type: Javadoc, dependsOn: jar) {
    doLast {
        copy {
            from  "${projectDir}/doc/javadoc/logos"
            into "${buildDir}/docs/javadocModules/logos"
        }
    }

    project.configure(options) {
        memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED
        charSet = "UTF-8"
        author="true"
        version="true"
        source= java_target_version
        linkSource="false"
        docTitle="OpenCms Workplace Modules API, version $ocmsVersion"
        windowTitle="OpenCms Workplace Modules API, version $ocmsVersion"
        header = "<script type=\"text/javascript\"> if (window.location.href.indexOf(\"overview-frame\") == -1) { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.alkacon.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/Alkacon.svg\\\" /></a>\"); } else { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.opencms.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/OpenCms.svg\\\" /></a>\"); }</script>"
    }
    source = sourceSets.modules.allJava
    classpath = project.sourceSets.modules.compileClasspath
    destinationDir = file("${buildDir}/docs/javadocModules")
}

task javadocJarModules(type: Jar, dependsOn: javadocModules) {
    archiveClassifier = 'javadoc'
    from "${buildDir}/docs/javadocModules"
    archiveBaseName = 'opencms-modules'
}

task sourcesJarModules(type: Jar) {
    from sourceSets.modules.java.srcDirs
    archiveClassifier = 'sources'
    archiveBaseName = 'opencms-modules'
}

task javadocGwt(type: Javadoc, dependsOn: jar) {
    doLast {
        copy {
            from  "${projectDir}/doc/javadoc/logos"
            into "${buildDir}/docs/javadocGwt/logos"
        }
    }

    project.configure(options) {
        memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED
        charSet = "UTF-8"
        author="true"
        version="true"
        source= java_target_version
        linkSource="false"
        docTitle="OpenCms GWT Components API, version $ocmsVersion"
        windowTitle="OpenCms GWT Components API, version $ocmsVersion"
        header = "<script type=\"text/javascript\"> if (window.location.href.indexOf(\"overview-frame\") == -1) { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.alkacon.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/Alkacon.svg\\\" /></a>\"); } else { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.opencms.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/OpenCms.svg\\\" /></a>\"); }</script>"
    }
    source = sourceSets.gwt.allJava
    classpath = project.sourceSets.gwt.compileClasspath
    destinationDir = file("${buildDir}/docs/javadocGwt")
}

task javadocJarGwt(type: Jar, dependsOn: javadocGwt) {
    archiveClassifier = 'javadoc'
    from "${buildDir}/docs/javadocGwt"
    archiveBaseName = 'opencms-gwt'
}

task sourcesJarGwt(type: Jar) {
    from sourceSets.gwt.java.srcDirs
    from (sourceSets.main.java.srcDirs){
        include '**/shared/**'
        include '**/gwt/CmsRpcException.java'
        include '**/ade/detailpage/CmsDetailPageInfo.java'
        include '**/db/CmsResourceState.java'
        include '**/jsp/CmsContainerJsonKeys.java'
        include '**/util/CmsPair.java'
        include '**/util/CmsDefaultSet.java'
        include '**/xml/content/CmsXmlContentProperty.java'
        include '**/workplace/editors/CmsTinyMceToolbarHelper.java'
    }
    includeEmptyDirs false
    archiveClassifier = 'sources'
    archiveBaseName = 'opencms-gwt'
}

task workplaceTheme (type: JavaExec) {
    doFirst {
        println '======================================================'
        println "Building workplace theme"
        println "Generating $project.buildDir/workplaceThemes/opencms/styles.css"
        println '======================================================'
        def dir = file("$project.buildDir/workplaceThemes/opencms")
        if (dir.exists()){
            delete(dir)
        }
        dir.mkdirs()
    }

    mainClass = 'com.vaadin.sass.SassCompiler'

    classpath {
        [
            sourceSets.gwt.compileClasspath
        ]
    }


    args = [
        "$projectDir/webapp/workplaceThemes/VAADIN/themes/opencms/styles.scss",
        "$project.buildDir/workplaceThemes/opencms/styles.css"
    ]
    maxHeapSize = max_heap_size
}
task opencmsFonts (type: JavaExec) {
    doFirst {
        println '======================================================'
        println "Building OpenCms fonts CSS"
        println "Generating $project.buildDir/workplaceThemes/opencmsFonts/opencmsFonts.css"
        println '======================================================'
        def dir = file("$project.buildDir/workplaceThemes/opencmsFonts")
        if (dir.exists()){
            delete(dir)
        }
        dir.mkdirs()
    }

    mainClass = 'com.vaadin.sass.SassCompiler'

    classpath {
        [
            sourceSets.gwt.compileClasspath
        ]
    }

    // opencmsFonts are generated into a different directory than the /opencms/styles.css
    // to avoid conflicts or dependencies between the build tasks 'workplaceTheme' and 'opencmsFonts'
    args = [
        "$projectDir/webapp/workplaceThemes/VAADIN/themes/opencms/opencmsFonts.scss",
        "$project.buildDir/workplaceThemes/opencmsFonts/opencmsFonts.css"
    ]
    maxHeapSize = max_heap_size
}


Properties gwtProps = new Properties()
gwtProps.load(new FileInputStream("$projectDir/src-gwt/gwt-modules.properties"))
project.ext.gwtModuleNames = gwtProps['gwtmodules']

task resourcesJar(type: Jar, dependsOn: [workplaceTheme, opencmsFonts]){
    doFirst {
        println '======================================================'
        println "Building Resources Jar"
        println '======================================================'
    }
    archiveBaseName = 'opencms-resources'
    archiveFileName = 'opencms-resources.jar'
    group 'OpenCms core JARs'
    allModuleNames.each{ moduleName ->
        from ("${projectDir}/modules/${moduleName}/static"){
            into "OPENCMS"
        }
    }
    from ("${projectDir}/webapp/workplaceThemes"){
        exclude '**/*.scss'
    }
    from ("${project.buildDir}/workplaceThemes/opencms"){
        into 'VAADIN/themes/opencms'
    }
    from ("${project.buildDir}/workplaceThemes/opencmsFonts"){
        into 'VAADIN/themes/opencms'
    }
    gwtModuleNames.split(',').each{ gwtModule ->
        if (!'org.opencms.ui.WidgetSet'.equals(gwtModule)){
            from( "${project.buildDir}/gwt/${gwtModule}") {
                exclude '**/WEB-INF/**'
                into "OPENCMS/gwt"
            }
        }
    }

    from ("${project.buildDir}/gwt/org.opencms.ui.WidgetSet"){
        include 'org.opencms.ui.WidgetSet/**'
        into 'VAADIN/widgetsets'
    }

    doLast {
        if (project.hasProperty('tomcat_update_target') && file(tomcat_update_target).exists()){
            println "copying ${project.buildDir}/libs/${archiveName} to ${tomcat_update_target}"
            copy {
                from  "${project.buildDir}/libs/${archiveName}"
                into tomcat_update_target
            }
        }
    }
}

// iterate gwt modules and create the required tasks
gwtModuleNames.split(',').each{ gwtModule ->
    task "gwt_${gwtModule}" (dependsOn: gwtClasses, type: JavaExec) {
        ext.buildDir =  project.buildDir.toString()  +"/gwt/${gwtModule}"
        ext.extraDir =  project.buildDir.toString() + "/extra/${gwtModule}"
        inputs.files sourceSets.gwt.java.srcDirs
        inputs.dir sourceSets.gwt.output.resourcesDir
        outputs.dir buildDir

        // Workaround for incremental build (GRADLE-1483)
        outputs.upToDateSpec = new org.gradle.api.specs.AndSpec()

        doFirst {
            println '======================================================'
            println "Building GWT resources for ${gwtModule}"
            println '======================================================'
            // to clean the output directory, delete it first
            def dir = file(buildDir)
            if (dir.exists()){
                delete(dir)
            }
            dir.mkdirs()
        }

        mainClass = 'com.google.gwt.dev.Compiler'

        classpath {
            [
                // Java source core
                sourceSets.main.java.srcDirs,
                // Java source gwt
                sourceSets.gwt.java.srcDirs,
                // Java source modules
                sourceSets.modules.java.srcDirs,
                // Generated resources
                sourceSets.gwt.output.resourcesDir,
                // Generated classes
                sourceSets.gwt.java.classesDirectory,
                // Dependecies
                sourceSets.gwt.compileClasspath,
            ]
        }


        if (project.hasProperty('gwtDraft')) {
            println "Using GWT draft mode for module $gwtModule"
            args =
                    [
                        gwtModule,
                        // Your GWT module
                        '-war',
                        buildDir,
                        '-logLevel',
                        'ERROR',
                        '-localWorkers',
                        '2',
                        '-style',
                        'obfuscated',
                        '-extra',
                        extraDir,
                        '-draftCompile',
                        // Speeds up compile with 25%
                        '-setProperty',
                        'locale=en'
                    ]
        } else {
            args =
                    [
                        gwtModule,
                        // Your GWT module
                        '-war',
                        buildDir,
                        '-logLevel',
                        'ERROR',
                        '-localWorkers',
                        '2',
                        '-style',
                        'obfuscated',
                        '-extra',
                        extraDir,
                        '-strict'
                    ]
        }
        jvmArgs = [
            '-Dgwt.jjs.permutationWorkerFactory=com.google.gwt.dev.ThreadedPermutationWorkerFactory'
        ]

        maxHeapSize = max_heap_size
    }

    tasks['resourcesJar'].dependsOn(tasks["gwt_${gwtModule}"])
}



task setupJar(dependsOn: jar, type: Jar) {
    from sourceSets.setup.output
    archiveFileName = 'opencms-setup.jar'
    archiveBaseName = 'opencms-setup'
    group 'OpenCms core JARs'
    exclude '**/.gitignore'
}

task javadocSetup(type: Javadoc, dependsOn: jar) {
    source = sourceSets.setup.allJava
    classpath = project.sourceSets.setup.compileClasspath
    destinationDir = file("${buildDir}/docs/javadocSetup")
    doLast {
        copy {
            from  "${projectDir}/doc/javadoc/logos"
            into "${buildDir}/docs/javadocSetup/logos"
        }
    }

    project.configure(options) {
        memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED
        charSet = "UTF-8"
        author="true"
        version="true"
        source= java_target_version
        linkSource="false"
        docTitle="OpenCms Setup API, version $ocmsVersion"
        windowTitle="OpenCms Setup API, version $ocmsVersion"
        header = "<script type=\"text/javascript\"> if (window.location.href.indexOf(\"overview-frame\") == -1) { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.alkacon.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/Alkacon.svg\\\" /></a>\"); } else { document.write(\"<a id=\\\"brandingLink\\\" target=\\\"_blank\\\" href=\\\"http://www.opencms.com\\\"><img border=\\\"0\\\" id=\\\"brandingPic\\\" src=\\\"{@docRoot}/logos/OpenCms.svg\\\" /></a>\"); }</script>"
    }
}

task javadocJarSetup(type: Jar, dependsOn: javadocSetup) {
    archiveClassifier = 'javadoc'
    from "${buildDir}/docs/javadocSetup"
    archiveBaseName = 'opencms-setup'
}

task sourcesJarSetup(type: Jar) {
    from sourceSets.setup.java.srcDirs
    archiveClassifier = 'sources'
    archiveBaseName = 'opencms-setup'
}

tlddoc {
    source 'webapp/WEB-INF/opencms.tld'
}


task tlddocZip (type: Zip, dependsOn: tlddoc) {
    archiveFileName = 'tld.zip'
    from ("${project.docsDir}/tlddoc/") {
        include '**/*'
    }
    destinationDirectory = file("${project.docsDir}")
}

def preserveLibModules = ''
def localeModules = []

// iterate all available modules and create the required tasks
allModuleNames.each{ moduleName ->
    def modulePackages = moduleName
    def moduleFolder = file("${projectDir}/modules/${moduleName}")
    def propertyFile = file("${moduleFolder}/module.properties")
    def gwtRename = null
    def workplacelocalization=null;
    if (propertyFile.exists()){
        Properties moduleProperties= new Properties()
        moduleProperties.load(new FileInputStream(propertyFile))
        if (moduleProperties['workplacelocalization']!=null){
            workplacelocalization=moduleProperties['workplacelocalization']
        }
    }
    def manifestFile = file("${moduleFolder}/resources/manifest.xml")
    def moduleDependencies=[]
    def moduleVersion = version
    if (manifestFile.exists()){
        def parsedManifest= (new XmlParser()).parse("${moduleFolder}/resources/manifest.xml")
        parsedManifest.module[0].dependencies[0].dependency.each{ dep ->
            moduleDependencies.add(dep.@name)
        }
        moduleVersion = parsedManifest.module[0].version[0].text()
    }
    def staticFolder=file("${moduleFolder}/static")
    if (workplacelocalization!=null){
        localeModules.add("${moduleName}")
        preserveLibModules += "${moduleName},"
    }

    task "dist_$moduleName" (type: Zip){
        ext.moduleName = moduleName
        ext.moduleFolder = moduleFolder
        ext.dependencies = moduleDependencies

        if (project.hasProperty('noVersion')) {
            archiveVersion = ""
        } else {
            archiveVersion = moduleVersion
        }
        destinationDirectory = modulesDistsDir

        // excluding jars from modules, jars will be placed in the WEB-INF lib folder through the moduleDeps configuration
        from("${moduleFolder}/resources"){
            exclude '**/lib*/*.jar'
        }

        // TODO: set the module version to match the manifest.xml
        archiveBaseName = moduleName
        group 'OpenCms module ZIPs'
        doFirst {
            println '======================================================'
            println "Building ZIP for $moduleName version $moduleVersion"
            println '======================================================'
        }
        doLast {
            if (project.hasProperty('module_copy_target') && file(module_copy_target).exists()){
                println "copying ${project.buildDir}/modulesZip/${archiveName} to ${module_copy_target}"
                copy {
                    from  "${project.buildDir}/modulesZip/${archiveName}"
                    into module_copy_target
                }
            }
        }
    }
    if (workplacelocalization != null){
        task "jar_$moduleName" (type: Jar) {
            ext.moduleName = moduleName
            ext.workplacelocalization=workplacelocalization
            manifest {
                attributes 'Implementation-Title': 'Alkacon OpenCms', 'Implementation-Version': archiveVersion
                if (workplacelocalization!=null) {
                    attributes 'OpenCms-Localization': workplacelocalization
                }
            }
            from ("$moduleFolder/resources/system/workplace/locales/$workplacelocalization/messages")
            archiveFileName = moduleName+'.jar'
            archiveBaseName = moduleName
            group 'OpenCms module JARs'
            exclude '**/.gitignore'
            doFirst{
                println '======================================================'
                println "Building ${moduleName}.jar including $modulePackages"
                println '======================================================'
            }

            doLast {
                if (project.hasProperty('tomcat_update_target') && file(tomcat_update_target).exists()){
                    println "copying ${project.buildDir}/libs/${archiveName} to ${tomcat_update_target}"
                    copy {
                        from  "${project.buildDir}/libs/${archiveName}"
                        into tomcat_update_target
                    }
                }
            }
        }
        tasks["dist_$moduleName"].dependsOn("jar_$moduleName")
    }
}

task allModules(dependsOn: tasks.matching{ Task task -> task.name.startsWith('dist_')}) {
    doLast {
        println '======================================================'
        println 'Done building modules'
        println '======================================================'
    }
}

task war (dependsOn: [
    setupJar,
    resourcesJar,
    modulesJar,
    allModules
], type: Zip){

    if (hasExtModules) {
        dependsOn {
            ':extmodules:bindist'
        }
    }
    archiveFileName = 'opencms.war'
    archiveBaseName = 'opencms-webapp'
    archiveExtension = 'war'
    ext.localeModules=localeModules;

    from ("${projectDir}/webapp"){
        // exclude the database drivers
        exclude '**/setupdata/**/*.jar'
        exclude '**/updatedata/**'
        exclude '**/workplaceThemes/**'
        exclude '**/classes/META-INF/**'
        exclude '**/solr/**'
        exclude '**/spellcheck/**'
        exclude '**/*.html'
        exclude '**/*.properties'
        exclude '**/*.txt'
        exclude '**/*.xml'
    }

    // copy SOLR config files separately to avoid the replace filter corrupting them
    from ("${projectDir}/webapp/WEB-INF/solr"){
        into '/WEB-INF/solr/'
    }

    from ("${projectDir}/webapp"){
        exclude '**/updatedata/**'
        exclude '**/workplaceThemes/**'
        exclude '**/solr/**'
        exclude '**/spellcheck/**'
        exclude 'WEB-INF/sun-jaxws.xml'
        include '**/*.html'
        include '**/*.properties'
        include '**/*.txt'
        include '**/*.xml'
        filter(ReplaceTokens, tokens: [
            OPENCMS_VERSION_NUMBER: project.version,
            OPENCMS_VERSION: product_name+' '+ project.version,
            DRIVERS_VFS: drivers_vfs,
            DRIVERS_PROJECT: drivers_project,
            DRIVERS_USER: drivers_user,
            DRIVERS_HISTORY: drivers_history,
            DRIVERS_CONFIGURATION: drivers_configuration,
            DRIVERS_SUBSCRIPTION: drivers_subscription,
            ADDITIONAL_DB_POOLS: db_additional_pools,
            OPENCMS_CONFIGURATION: opencms_configuration,
            RUNTIME_INFO: system_runtimeinfo,
            COMMENT_UPDATER_START: '',
            COMMENT_UPDATER_END: '',
            COMMENT_WAR_START: '<!--',
            COMMENT_WAR_END: '-->'
        ])
    }

    from ("${project.buildDir}/libs") {
        include '*.jar'
        exclude 'opencms-gwt*.jar'
        exclude 'opencms-test*.jar'
        exclude '*-sources.jar'
        exclude '*-javadoc.jar'
        into '/WEB-INF/lib'
    }

    into ('/WEB-INF/lib') { from configurations.distribution }
    into ('/WEB-INF/lib') { from configurations.moduleDeps }
    into ('/WEB-INF/lib/apis') { from configurations.usedApis }

    fileTree('webapp/WEB-INF/setupdata/database'){ include '**/*.jar'}.each {File driverJar ->
        // copy the database drivers into the lib folder
        from (driverJar.path) { into '/WEB-INF/lib' }
    }

    from (modulesDistsDir) {
        into '/WEB-INF/packages/modules'
        localeModules.each{ localeModule ->
            exclude "${localeModule}*.zip"
        }
    }

    from("${projectDir}/lib/jni") { into "/WEB-INF/lib/jni" }

    if (hasExtModules) {
        // Note that the module deps do not need to be copied
        // since they are contained in configurations.moduleDeps
        def extModulesDir = "${extModulesProject.buildDir}/modules"
        from ("${extModulesDir}/libs") {
            include '*.jar'
            into '/WEB-INF/lib'
        }
        from ("${extModulesDir}/modulesZip") {
            into '/WEB-INF/packages/modules'
        }
    }
}

task updater (dependsOn: [
    setupJar,
    resourcesJar,
    modulesJar,
    allModules
], type: Zip){
    if (hasExtModules) {
        // without this declaration, Gradle 8 complains about implicit dependencies
        dependsOn {
            ':extmodules:bindist'
        }
    }

    dependsOn {
        tasks.matching{dist_task -> dist_task.name.startsWith('dist_')}
    }

    archiveBaseName = 'opencms-upgrade-to'
    ext.preserveLibModules = preserveLibModules

    // adds empty JAR files for all deprecated or updated libs
    Properties buildProps = new Properties()
    buildProps.load(new FileInputStream("${projectDir}/build-default.properties"))
    buildProps['updater.jars.remove'].split(',').each{ jar ->
        from("${projectDir}/webapp/WEB-INF/updatedata/empty.jar"){
            into '/WEB-INF/lib'
            rename('empty\\.jar', jar)
        }
    }

    // only process the text files with the ReplaceTokens filter, copy everything else in a second from clause
    from ("${projectDir}/webapp"){
        include 'WEB-INF/updatedata/**/*.ori'
        include 'WEB-INF/updatedata/**/*.html'
        include 'WEB-INF/updatedata/**/*.xml'
        include 'WEB-INF/updatedata/**/*.txt'
        include 'WEB-INF/updatedata/**/*.jsp'
        exclude 'WEB-INF/updatedata/config/opencms.xml'
        exclude 'WEB-INF/updatedata/readme.txt'
        exclude 'WEB-INF/updatedata/empty.jar'
        filter(ReplaceTokens, tokens: [
            OPENCMS_VERSION_NUMBER: project.version,
            OPENCMS_VERSION: product_name+' '+ project.version,
            PRESERVE_LIB_MODULES: preserveLibModules
        ])
    }

    from ("${projectDir}/webapp"){
        include 'WEB-INF/updatedata/**'
        exclude 'WEB-INF/updatedata/**/*.ori'
        exclude 'WEB-INF/updatedata/**/*.html'
        exclude 'WEB-INF/updatedata/**/*.xml'
        exclude 'WEB-INF/updatedata/**/*.txt'
        exclude 'WEB-INF/updatedata/**/*.jsp'
        exclude 'WEB-INF/updatedata/config/opencms.xml'
        exclude 'WEB-INF/updatedata/readme.txt'
        exclude 'WEB-INF/updatedata/empty.jar'
    }

    from ("${projectDir}/webapp/WEB-INF/classes/log4j2.xml") {
        into '/WEB-INF/classes'
    }

    from ("${projectDir}/webapp/WEB-INF/updatedata/config/opencms.xml") {
        into '/WEB-INF/config'
    }

    from("${projectDir}/webapp/WEB-INF/config/opencms-workplace.xml"){
        into '/WEB-INF/config/defaults'
    }

    from("${projectDir}/webapp/WEB-INF/config/opencms-vfs.xml"){
        into '/WEB-INF/config/defaults'
    }

    from("${projectDir}/webapp/WEB-INF/config/opencms-importexport.xml"){
        into '/WEB-INF/config/defaults'
    }

    from("${projectDir}/webapp/WEB-INF/config/opencms-system.xml"){
        into '/WEB-INF/config/defaults'
    }

    from("${projectDir}/webapp/WEB-INF/config/opencms-search.xml"){
        into '/WEB-INF/config/defaults'
    }

    from ("${projectDir}/webapp/WEB-INF/solr"){
        into '/WEB-INF/solr-update/'
        include '*'
        include '**/*'
    }

    from ("${projectDir}/webapp/WEB-INF/updatedata/readme.txt"){
        filter(ReplaceTokens, tokens: [
            OPENCMS_VERSION_NUMBER: project.version,
            OPENCMS_VERSION: product_name+' '+ project.version
        ])
    }
    from ("${projectDir}/webapp/WEB-INF"){
        into '/WEB-INF'
        include 'opencms.tld'
        exclude 'web.xml'
        include 'cmsshell.sh'
        include 'classes/META-INF/persistence.xml'
        include 'classes/ehcache.xml'
        include 'classes/repository.properties'
        include 'sun-jaxws.xml'
        include 'spellcheck/**'
        include 'git-scripts/**'
    }
    from ("${projectDir}/webapp/WEB-INF"){
        into '/WEB-INF'
        include 'web.xml'
        filter(ReplaceTokens, tokens: [
            COMMENT_UPDATER_START: '<!-- ',
            COMMENT_UPDATER_END: '-->',
            COMMENT_WAR_START: '',
            COMMENT_WAR_END: ''
        ])
    }
    from ("${projectDir}/webapp/resources"){
        into '/resources'
        include '*'
        include '**/*'
    }
    from ("${project.buildDir}/libs") {
        include '*.jar'
        exclude 'opencms-test*.jar'
        exclude 'opencms-gwt*.jar'
        exclude '*-sources.jar'
        exclude '*-javadoc.jar'
        into '/WEB-INF/lib'
    }
    into ('/WEB-INF/lib') {
        from configurations.distribution
    }

    from (modulesDistsDir) {
        into '/WEB-INF/updatedata/modules'
        localeModules.each{ localeModule ->
            exclude "${localeModule}*.zip"
        }
        exclude "*mercury*.zip"
    }

    fileTree('webapp/WEB-INF/setupdata/database'){ include '**/*.jar'}.each {File driverJar ->
        // copy the database drivers into the lib folder
        from (driverJar.path) { into '/WEB-INF/lib' }
    }
}

task bindist (dependsOn: war, type: Zip){
    archiveBaseName = 'opencms'
    from "${project.buildDir}/distributions/opencms.war"
    from(projectDir) {
        include 'INSTALL.md'
        include 'LICENSE'
        include 'README.md'
        include 'history.txt'
        filter(ReplaceTokens, tokens: [
            OPENCMS_VERSION_NUMBER: project.version,
            OPENCMS_VERSION: product_name+' '+ project.version
        ])
    }
}


test {
    // We fix max heap size here, since with less heap size tests will fail.
    maxHeapSize = "2000m"
    useJUnit()
    scanForTestClasses false
    testClassesDirs = files(sourceSets.test.java.classesDirectory)
    systemProperties['test.data.path'] = "${projectDir}/test/data"
    systemProperties['test.webapp.path'] = "${projectDir}/webapp"
    systemProperties['test.project.path'] = "${projectDir}"
    systemProperties['test.build.folder'] =sourceSets.test.output.resourcesDir
    testLogging.showStandardStreams = true
    ignoreFailures true
    filter {
        includeTestsMatching "org.opencms.test.AllTests"
    }
}

task testSingle(type: Test, dependsOn: [compileTestJava]) {
    description "Runs a specified test case set like this: -PtestCaseToRun=org.opencms.main.TestCmsSystemInfo*"
    inputs.dir "${projectDir}/test/data"
    inputs.dir "${projectDir}/webapp"

    useJUnit()
    if (!project.hasProperty('testCaseToRun')){
        project.ext.testCaseToRun='org.opencms.main.TestCmsSystemInfo*'
    }
    doFirst{
        println "Running test case : ${testCaseToRun}"
    }
    filter {
        includeTestsMatching testCaseToRun
    }
    scanForTestClasses false
    testClassesDirs = files(sourceSets.test.java.classesDirectory)
    systemProperties['test.data.path'] = "${projectDir}/test/data"
    systemProperties['test.webapp.path'] = "${projectDir}/webapp"
    systemProperties['test.build.folder'] =sourceSets.test.output.resourcesDir
    maxHeapSize = max_heap_size
    testLogging.showStandardStreams = true
    ignoreFailures true
}

task testJar(dependsOn: compileTestJava, type: Jar) {
    from sourceSets.test.output
    archiveBaseName = 'opencms-test'
    exclude '**/.gitignore'
    exclude '**/*.java'
}

task javadocTest(type: Javadoc, dependsOn: jar) {
    source = sourceSets.test.allJava
    classpath = project.sourceSets.test.compileClasspath
    destinationDir = file("${buildDir}/docs/javadocTest")
}

task javadocJarTest(type: Jar, dependsOn: javadocTest) {
    archiveClassifier = 'javadoc'
    from "${buildDir}/docs/javadocTest"
    archiveBaseName = 'opencms-test'
}

task sourcesJarTest(type: Jar) {
    from sourceSets.test.java.srcDirs
    archiveClassifier = 'sources'
    archiveBaseName = 'opencms-test'
}


task testGwt(type: Test, dependsOn: [compileTestGwtJava]) {
    classpath=sourceSets.testGwt.runtimeClasspath
    classpath += files("${projectDir}/src")
    classpath += files("${projectDir}/src-gwt")
    classpath += files("${projectDir}/test-gwt")
    useJUnit()
    filter {
        includeTestsMatching 'org.opencms.client.test.AllTests'
    }
    scanForTestClasses false
    testClassesDirs = files(sourceSets.testGwt.java.classesDirectory)
    systemProperties['gwt.args'] = "-logLevel WARN -setProperty locale=en"
    systemProperties['java.awt.headless'] = "true"
    maxHeapSize = max_heap_size
    testLogging.showStandardStreams = true
    ignoreFailures true
}

artifacts {
    archives sourcesJar

	if (gradle.startParameter.taskNames.contains("uploadArchives")) {
        // do not include the war if only running the install task, it takes ages to build
        archives war
        archives resourcesJar
    }

    archives setupJar
    archives sourcesJarSetup

    archives modulesJar
    archives sourcesJarModules

    archives gwtJar
    archives sourcesJarGwt

    archives testJar
    archives sourcesJarTest

    tasks.each { task ->
        if (task.name.startsWith("jar_org.opencms.")){
            def moduleName=task.archiveBaseName
            archives task
            if (tasks.hasProperty("sourcesJar_$moduleName")) {
                archives tasks["sourcesJar_$moduleName"]
            }
        }
    }
    // in case the property 'skip_javadoc' is set to 'true', javadoc generation is skipped - this is supposed to speed up build time for CI
    if (addJavadoc) {
        archives javadocJar
        archives javadocJarSetup
        archives javadocJarModules
        archives javadocJarGwt
        archives javadocJarTest
        tasks.each { task ->
            if (task.name.startsWith("jar_org.opencms.")) {
                def moduleName=task.archiveBaseName
                if (tasks.hasProperty("javadocJar_$moduleName")) {
                    archives tasks["javadocJar_$moduleName"]
                }
            }
        }
    }
}


publishing {
    publications { pubs ->
        core(MavenPublication) {
            from components.java
            artifact sourcesJar
            if (addJavadoc) artifact javadocJar
            pom {
                name = product_name
                description = product_description
                packaging 'jar'
                groupId 'org.opencms'
                url = 'http://www.opencms.org'
                scm {
                    url = 'scm:git@github.com:alkacon/opencms-core.git'
                    connection = 'scm:git@github.com:alkacon/opencms-core.git'
                    developerConnection = 'scm:git@github.com:alkacon/opencms-core.git'
                }
                licenses {
                    license {
                        name = 'GNU Lesser General Public License'
                        url = 'http://www.gnu.org/licenses/lgpl.html'
                        distribution = 'repo'
                    }
                }
                organization {
                    name = 'Alkacon Software'
                    url = 'https://www.alkacon.com'
                }
                developers {
                    developer {
                        name = 'Alkacon Software'
                        url = 'https://www.alkacon.com'
                    }
                }
                withXml {
                    // Update dependencies with resolved versions
                    def hasDependencies = !asNode().dependencies.isEmpty()
                    if (hasDependencies) {
                        // for some reason Gradle incorrectly sets the scope to 'runtime' for some dependencies, so we fix it
                        // (if we didn't do this, the dependencies would be missing in dependent projects)
                        asNode().dependencies.'*'.each() { dep ->
                            if (dep.scope.text() == 'runtime' && dep.artifactId.text() in [
                                        'javax.servlet-api',
                                        'javax.servlet.jsp-api'
                                    ]) {
                                println("Correcting scope for dependency ${dep.artifactId.text()}")
                                dep.scope.first().setValue('compile')
                            }
                        }

                        // add additional repositories to search artifacts in
                        def repositoriesNode = asNode().appendNode('repositories')
                        def respositoryNode = repositoriesNode.appendNode('repository')
                        respositoryNode.appendNode('id', 'vaadin-addons');
                        respositoryNode.appendNode('url', 'https://maven.vaadin.com/vaadin-addons');
                        respositoryNode = repositoriesNode.appendNode('repository')
                        respositoryNode.appendNode('id', 'restlet');
                        respositoryNode.appendNode('url', 'https://maven.restlet.org');
                    }
                }
            }
        }
        /*versionMapping {
         usage('api') {
         fromResolutionOf(configurations.distribution)
         }
         usage('runtime') {
         fromResolutionOf(configurations.distribution)
         }
         }*/
        def furtherPubs = [
            "setup" : [
                "artifacts" : addJavadoc ? [
                    setupJar,
                    sourcesJarSetup,
                    javadocJarSetup
                ] : [setupJar, sourcesJarSetup]
            ],
            "modules" : [
                "artifacts" : addJavadoc ? [
                    modulesJar,
                    sourcesJarModules,
                    javadocJarModules
                ] : [
                    modulesJar,
                    sourcesJarModules
                ]
            ],
            "gwt" : [
                "artifacts" : addJavadoc ? [
                    gwtJar,
                    sourcesJarGwt,
                    javadocJarGwt
                ] : [gwtJar, sourcesJarGwt]
            ],
            "test" : [
                "artifacts" : addJavadoc ? [
                    testJar,
                    sourcesJarTest,
                    javadocJarTest
                ] : [testJar, sourcesJarTest]
            ]
        ]
        furtherPubs.each { pub ->
            pubs.create(pub.key, MavenPublication) {
                pub.value.artifacts.each { art ->
                    artifact art
                }
                pom {
                    artifactId "opencms-${pub.key}"
                    name = product_name
                    description = product_description
                    packaging 'jar'
                    groupId 'org.opencms'
                    url = 'http://www.opencms.org'
                    scm {
                        url = 'scm:git@github.com:alkacon/opencms-core.git'
                        connection = 'scm:git@github.com:alkacon/opencms-core.git'
                        developerConnection = 'scm:git@github.com:alkacon/opencms-core.git'
                    }
                    licenses {
                        license {
                            name = 'GNU Lesser General Public License'
                            url = 'http://www.gnu.org/licenses/lgpl.html'
                            distribution = 'repo'
                        }
                    }
                    organization {
                        name = 'Alkacon Software'
                        url = 'https://www.alkacon.com'
                    }
                    developers {
                        developer {
                            name = 'Alkacon Software'
                            url = 'https://www.alkacon.com'
                        }
                    }

                    if (pub.key == 'gwt') {
                        withXml { xml ->
                            def deps = xml.asNode().appendNode('dependencies');
                            def dependenciesGwt=project.configurations.gwtCompile.dependencies
                            dependenciesGwt.each { dep ->
                                if (dep instanceof ExternalModuleDependency) {
                                    def dependency = deps.appendNode('dependency')
                                    dependency.appendNode('groupId', dep.group)
                                    dependency.appendNode('artifactId', dep.name)
                                    dependency.appendNode('version', dep.version)
                                }
                            }
                            def dependencyNode = deps.appendNode('dependency')
                            dependencyNode.appendNode('artifactId','opencms-core')
                            dependencyNode.appendNode('groupId','org.opencms')
                            dependencyNode.appendNode('version',version)
                        }
                    } else {
                        withXml {
                            def hasDependencies = !asNode().dependencies.isEmpty()
                            if (hasDependencies) {
                                asNode().removeChild(asNode().dependencies)
                            }
                            def dependenciesNode = asNode().appendNode('dependencies')
                            def dependencyNode = dependenciesNode.appendNode('dependency')
                            dependencyNode.appendNode('artifactId','opencms-core')
                            dependencyNode.appendNode('groupId','org.opencms')
                            dependencyNode.appendNode('version',version)
                        }
                    }
                }
            }
        }
        if (gradle.startParameter.taskNames.contains("uploadArchives")) {
            webapp(MavenPublication) {
                artifact war
                pom {
                    artifactId 'opencms-webapp'
                    name = product_name
                    description = product_description
                    packaging 'war'
                    groupId 'org.opencms'
                    url = 'http://www.opencms.org'
                    scm {
                        url = 'scm:git@github.com:alkacon/opencms-core.git'
                        connection = 'scm:git@github.com:alkacon/opencms-core.git'
                        developerConnection = 'scm:git@github.com:alkacon/opencms-core.git'
                    }
                    licenses {
                        license {
                            name = 'GNU Lesser General Public License'
                            url = 'http://www.gnu.org/licenses/lgpl.html'
                            distribution = 'repo'
                        }
                    }
                    organization {
                        name = 'Alkacon Software'
                        url = 'https://www.alkacon.com'
                    }
                    developers {
                        developer {
                            name = 'Alkacon Software'
                            url = 'https://www.alkacon.com'
                        }
                    }
                }
            }
            pubs.each { pub ->
                signing.sign pub
            }
        }
    }
}


// add it to keep the old task names
task install(dependsOn: publishToMavenLocal) {
    doFirst {
        println "Installing artifacts for version $version"
    }
}

task uploadArchives { // dependency tasks are set dynamically via afterEvaluate
    doFirst {
        println "Upload artifacts for version $version"
    }
}


// fixed issue with libraries containing both .java and .class files
tasks.withType(JavaCompile) {
    options.sourcepath=files()
    options.encoding='UTF-8'
    options.incremental = true
}
tasks.withType(Javadoc) {
    options.addStringOption("sourcepath", "")
    if (JavaVersion.current().isJava8Compatible()) {
        options.addStringOption("Xdoclint:none", "-quiet")
        options.addBooleanOption("-allow-script-in-comments",true);
    }
    doLast {
        def searchScript = new File(destinationDir.getAbsolutePath() + '/search.js')
        searchScript.append "getURLPrefix = function(ui) { return ''; };"
    }
}
// all tasks implementing the CopySpec (Copy,Jar,Zip,...) should fail, in case they generate duplicate files
tasks.withType(CopySpec) {
    duplicatesStrategy 'fail'
}


// The Gradle module metadata generation ignores the non-transitiveness of our dependencies, just as the POM generation normally does.
// This leads to conflicts / build errors in dependent projects.
// We already manually fix it for the POM, but I don't know how to fix it for the module metadata generation.
// So just disable the module metadata - there is no benefit from it right now.
tasks.withType(GenerateModuleMetadata) {
    enabled = false
}


afterEvaluate {
	def uploadArchivesDeps = [tasks.findByName("publishToSonatype"), tasks.findByName("closeSonatypeStagingRepository")]
	tasks.findByName("uploadArchives").dependsOn(uploadArchivesDeps) 
}