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

// Workaround needed for nexus publishing bug
// version and group must be specified in the root project
// https://github.com/gradle-nexus/publish-plugin/issues/310
version = projectVersion
group = 'this.will.be.overridden'

def publishedProjects = [
        'grails-docs-core',
        'grails-gradle-bom',
        'grails-gradle-common',
        'grails-gradle-model',
        'grails-gradle-plugins',
        'grails-gradle-tasks',
]

subprojects {
    if (name in publishedProjects) {
        // This has to be applied here in the root project due to the nexus plugin requirements
        apply plugin: 'org.apache.grails.gradle.grails-publish'
    }
}

tasks.register('publishAllPublicationsToTestCaseMavenRepoRepository').configure {
    dependsOn(
            subprojects
                    .collect { p -> p.tasks.named('publishAllPublicationsToTestCaseMavenRepoRepository') }
    )
}

def aggregatePublishedArtifacts = tasks.register('aggregatePublishedArtifacts')

tasks.register('aggregateChecksums').configure {
    group = 'publishing'
    description = 'Aggregates all SHA-256 checksums from subprojects into a single file.'

    def outputFileProvider = rootProject.layout.buildDirectory.file('grails-gradle-checksums.txt')
    outputs.file(outputFileProvider)

    dependsOn(
            subprojects
                    .findResults { it.tasks.names.contains('publishedChecksums') ? "${it.path}:publishedChecksums" : null }
    )
    finalizedBy(aggregatePublishedArtifacts)

    outputs.upToDateWhen { false } // not worth caching

    doLast {
        def outputFile = outputFileProvider.get().asFile
        outputFile.withPrintWriter { writer ->
            subprojects.each { sub ->
                def checksumDir = sub.layout.buildDirectory.dir('checksums').get().asFile
                if (checksumDir.exists()) {
                    checksumDir.eachFileMatch(~/.*\.sha512/) {
                        def jarName = it.name - '.sha512'
                        def checksumLine = it.text.trim()
                        def checksum = checksumLine.tokenize().first()
                        writer.println("$jarName $checksum")
                    }
                }
            }
        }

        println "Checksum manifest written to ${outputFile}"
    }
}

aggregatePublishedArtifacts.configure {
    group = 'publishing'
    description = 'Aggregates all published artifacts from subprojects into a single file.'

    def outputFileProvider = rootProject.layout.buildDirectory.file('grails-gradle-artifacts.txt')
    outputs.file(outputFileProvider)

    outputs.upToDateWhen { false } // not worth caching

    dependsOn(subprojects.findResults { it.tasks.names.contains('savePublishedArtifacts') ? "${it.path}:savePublishedArtifacts" : null })

    doLast {
        def outputFile = outputFileProvider.get().asFile
        outputFile.text = '' // clear previous
        outputFile.withPrintWriter { writer ->
            subprojects.each { sub ->
                def artifactsDir = sub.layout.buildDirectory.dir('artifacts').get().asFile
                if (artifactsDir.exists()) {
                    artifactsDir.eachFileMatch(~/.*\.txt/) {
                        def artifactName = it.name - '.txt'
                        def coordinates = it.text.trim()
                        writer.println("$artifactName $coordinates")
                    }
                }
            }
        }

        println "Published artifacts written to ${outputFile}"
    }
}