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

import org.gradle.crypto.checksum.Checksum
import org.apache.grails.gradle.publish.GrailsPublishExtension

extensions.configure(GrailsPublishExtension) {
    // Explicit `it` is required here
    it.githubSlug = 'apache/grails-redis'
    it.license.name = 'Apache-2.0'
    it.title = 'Grails Redis Plugin'
    it.desc = 'This Plugin provides access to Redis and various utilities (service, annotations, etc) for caching.'
    it.developers = [
            tednaleid: 'Ted Naleid',
            burtbeckwith: 'Burt Beckwith',
            christianoestreich: 'Christian Oestreich',
            briancoles: 'Brian Coles',
            michaelcameron: 'Michael Cameron',
            johnengelman: 'John Engelman',
            davidseiler: 'David Seiler',
            jordonsaardchit: 'Jordon Saardchit',
            florianlangenhahn: 'Florian Langenhahn',
            germansancho: 'German Sancho',
            johnmulhern: 'John Mulhern',
            shaunjurgemeyer: 'Shaun Jurgemeyer',
            puneetbehl: 'Puneet Behl'
    ]
}


afterEvaluate {
    if (project.plugins.hasPlugin('signing')) {
        if(System.getenv('TEST_BUILD_REPRODUCIBLE')) {
            project.logger.lifecycle("Signing is disabled for this build to test build reproducibility.")
            project.tasks.withType(Sign).configureEach {
                it.enabled = false
            }
        }
    }
    if (project.plugins.hasPlugin("maven-publish")) {
        def checksumTask = tasks.register("publishedChecksums", Checksum)
        checksumTask.configure { Checksum check ->
            check.checksumAlgorithm = Checksum.Algorithm.SHA512
            check.outputDirectory.set(project.layout.buildDirectory.dir("checksums"))
            check.dependsOn(tasks.withType(Jar))
        }

        def artifactsDir = project.layout.buildDirectory.dir("artifacts")
        def artifactsTask = tasks.register("savePublishedArtifacts") {
            it.outputs.dir(artifactsDir)
            it.dependsOn(tasks.withType(Jar))
        }

        gradle.taskGraph.whenReady {
            List filesToChecksum = []
            publishing.publications.withType(MavenPublication).all { MavenPublication publication ->
                publication.artifacts.each { MavenArtifact artifact ->
                    if(artifact.file.name == 'grails-plugin.xml' || artifact.file.name == 'profile.yml') {
                        return
                    }
                    filesToChecksum << artifact.file
                }
            }

            checksumTask.configure { Checksum check ->
                check.inputFiles.setFrom(filesToChecksum.unique())
                check.finalizedBy(artifactsTask)

            }

            artifactsTask.configure {
                doLast {
                    Map<String, String> artifacts = [:]
                    project.publishing.publications.withType(MavenPublication).all { MavenPublication publication ->
                        publication.artifacts.each { MavenArtifact artifact ->
                            if(!artifact.file.exists() || artifact.file.name == 'grails-plugin.xml' || artifact.file.name == 'profile.yml') {
                                return
                            }

                            if(artifact.classifier) {
                                artifacts[artifact.file.name] = "${publication.groupId}:${publication.artifactId}:${publication.version}:${artifact.classifier}" as String
                            }
                            else {
                                artifacts[artifact.file.name] = "${publication.groupId}:${publication.artifactId}:${publication.version}" as String
                            }
                        }
                    }

                    File artifactsFile = artifactsDir.get().asFile
                    artifactsFile.mkdirs()

                    artifacts.entrySet().each { Map.Entry<String, String> entry ->
                        File published = new File(artifactsFile, "${entry.key}.txt" as String)
                        published.text = entry.value
                    }
                }
            }
        }

        Set<String> publishTasks = tasks.names.findAll { it.startsWith('publishMavenPublication') }
        publishTasks.each { taskName ->
            tasks.named(taskName).configure { publishTask ->
                publishTask.finalizedBy checksumTask
            }
        }
    }
}
