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

apply plugin: 'org.apache.grails.gradle.grails-publish'

grailsPublish {
    githubSlug = 'apache/grails-quartz'
    license.name = 'Apache-2.0'
    title = 'Grails Quartz Plugin'
    desc = 'This plugin allows your Grails application to schedule jobs to be executed using a specified interval or cron expression.'
    developers = [
            burtbeckwith: 'Burt Beckwith',
            jeffscottbrown: 'Jeff Scott Brown',
            graemerocher: 'Graeme Rocher',
            ryanvanderwerf: 'Ryan Vanderwerf',
            sergeynebolsin: 'Sergey Nebolsin',
            puneetbehl: 'Puneet Behl',
            vitaliisamolovskikh: 'Vitalii Samolovskikh'
    ]
}

afterEvaluate {
    if (plugins.hasPlugin('signing') && System.getenv('TEST_BUILD_REPRODUCIBLE')) {
        logger.lifecycle('Signing is disabled for this build to test build reproducibility.')
        tasks.withType(Sign).configureEach {
            enabled = false
        }
    }
    if (plugins.hasPlugin('maven-publish')) {
        def checksumTask = tasks.register('publishedChecksums', Checksum) {
            checksumAlgorithm = Checksum.Algorithm.SHA512
            outputDirectory = layout.buildDirectory.dir('checksums')
            dependsOn(tasks.withType(Jar))
        }
        def artifactsDir = layout.buildDirectory.dir('artifacts')
        def artifactsTask = tasks.register('savePublishedArtifacts') {
            outputs.dir(artifactsDir)
            dependsOn(tasks.withType(Jar))
        }

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

            checksumTask.configure { Checksum check ->
                check.inputFiles.from = filesToChecksum.unique()
                check.finalizedBy(artifactsTask)
            }

            artifactsTask.configure {
                doLast {
                    Map<String, String> artifacts = [:]
                    publishing.publications.withType(MavenPublication).configureEach { mavenPublication ->
                        mavenPublication.artifacts.each { artifact ->
                            if (!artifact.file.exists() || artifact.file.name == 'grails-plugin.xml' || artifact.file.name == 'profile.yml') {
                                return
                            }
                            if(artifact.classifier) {
                                artifacts[artifact.file.name] = "$groupId:$artifactId:$version:$artifact.classifier".toString()
                            }
                            else {
                                artifacts[artifact.file.name] = "$groupId:$artifactId:$version".toString()
                            }
                        }
                    }

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

                    artifacts.each {
                        File published = new File(artifactsFile, "${it.key}.txt")
                        published.text = it.value
                    }
                }
            }
        }

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


        def aggregatePublishedArtifacts = tasks.register('aggregatePublishedArtifacts')

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

            def outputFileProvider = rootProject.layout.buildDirectory.file("CHECKSUMS.txt")
            outputs.file(outputFileProvider)

            dependsOn(checksumTask)
            finalizedBy(aggregatePublishedArtifacts)

            outputs.upToDateWhen { false } // not worth caching

            doLast {
                def outputFile = outputFileProvider.get().asFile
                outputFile.withPrintWriter { writer ->
                    def checksumDir = 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 into a single file."

            def outputFileProvider = rootProject.layout.buildDirectory.file("PUBLISHED_ARTIFACTS.txt")
            outputs.file(outputFileProvider)

            outputs.upToDateWhen { false } // not worth caching

            dependsOn(artifactsTask)

            doLast {
                def outputFile = outputFileProvider.get().asFile
                outputFile.text = "" // clear previous
                outputFile.withPrintWriter { writer ->
                    def publishedArtifactsDir = artifactsDir.get().asFile
                    if (publishedArtifactsDir.exists()) {
                        publishedArtifactsDir.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}"
            }
        }
    }
}
