/*
 *  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 = [
        'acl-plugin',
        'cas-plugin',
        'core-plugin',
        'ldap-plugin',
        'oauth2-plugin',
        'spring-security-rest',
        'spring-security-rest-gorm',
        'spring-security-rest-grailscache',
        'spring-security-rest-memcached',
        'spring-security-rest-redis',
        'ui-plugin'
]
subprojects {
    version = projectVersion
    if (name in publishedProjects) {
        // This has to be applied here
        apply plugin: 'org.apache.grails.gradle.grails-publish'
    }
    else if (name == 'spring-security-rest-testapp-profile') {
        apply plugin: 'org.apache.grails.gradle.grails-publish-profile'
    }
}

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("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.listFiles(new FilenameFilter() {
                        boolean accept(File dir, String name) {
                            return name.endsWith(".sha512")
                        }
                    })?.each { checksumFile ->
                        def jarName = checksumFile.name - ".sha512"
                        def checksumLine = checksumFile.text.trim()
                        def checksum = checksumLine.tokenize()[0]
                        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("PUBLISHED_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.listFiles(new FilenameFilter() {
                        boolean accept(File dir, String name) {
                            return name.endsWith(".txt")
                        }
                    })?.each { checksumFile ->
                        def artifactName = checksumFile.name - ".txt"
                        def coordinates = checksumFile.text.trim()
                        writer.println("${artifactName} ${coordinates}")
                    }
                }
            }
        }

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