/*
 * Copyright 2021 DataCanvas
 *
 * Licensed 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
 *
 *     http://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.
 */

plugins {
    id 'distribution'
    id 'de.undercouch.download' version '5.4.0'
}

def jdkConfig = [
    'Linux-x64' : [
        url : 'https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_linux-x64_bin.tar.gz',
        dir : 'jdk-17.0.2+7'
    ],
    'Windows-x64' : [
        url : 'https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_windows-x64_bin.zip',
        dir : 'jdk-17.0.2+7'
    ],
    'Darwin-x64' : [
        url : 'https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_macos-x64_bin.tar.gz',
        dir : 'jdk-17.0.2+7/Contents/Home'
    ]
]

def down = project.hasProperty('isDownload') ? project.property('isDownload').toBoolean() : false

tasks.register('downloadJdk') {
    if (!down) {
        return
    }
    doLast {
        jdkConfig.each { platform, config ->
            def destFile = file("${buildDir}/jdk/${platform}.${config.url.split(/\./).last()}")
            def outputDir = file("${buildDir}/jdk/${platform}")

            download.run {
                src config.url
                dest destFile
                overwrite false
            }

            destFile.setReadable(true, false)
            destFile.setWritable(true)

            mkdir(outputDir)
            outputDir.setWritable(true, false)

            if (destFile.name.endsWith('.gz')) {
                copy {
                    from tarTree(resources.gzip(destFile))
                    into outputDir
                    eachFile { fcd ->
                        fcd.path = fcd.path.replaceFirst(/^[^\/]+\//, '')
                    }
                    includeEmptyDirs = false
                }
            } else if (destFile.name.endsWith('.zip')) {
                copy {
                    from zipTree(destFile)
                    into outputDir
                    eachFile { fcd ->
                        fcd.path = fcd.path.replaceFirst(/^[^\/]+\//, '')
                    }
                    includeEmptyDirs = false
                }
            }
            fileTree(outputDir).each { file ->
                file.setReadable(true, false)
                file.setExecutable(true, false)
            }
        }
    }
}

task copyDepends(type: Copy) {

    from(layout.projectDirectory) {
        include "conf/**"
        include "bin/**"
    }
    into layout.projectDirectory.dir("dingo")

    from(fileTree("${buildDir}/jdk")) {
        include('*-x64/**')
        exclude('*.gz')
        exclude('*.zip')
    }
    into layout.projectDirectory.dir("dingo")

    from(project(':dingo-executor').layout.buildDirectory) {
        include('libs/dingo-executor-*-all.jar')
    }
    into layout.projectDirectory.dir("dingo")

    from(project(':dingo-driver:dingo-driver-client').layout.buildDirectory) {
        include('libs/dingo-driver-client-*-all.jar')
    }
    into layout.projectDirectory.dir("dingo")

    from(project(':dingo-web').layout.buildDirectory) {
        include("libs/dingo-web-*.jar")
        exclude("libs/dingo-web-*-plain.jar")
    }
    into layout.projectDirectory.dir("dingo")

    from(project(':dingo-example').layout.buildDirectory) {
        include("libs/dingo-example-*-all.jar")
    }
    into layout.projectDirectory.dir("dingo")

    from(project(':dingo-net-netty').layout.buildDirectory) {
        include("libs/dingo-net-*-all.jar")
    }
    into layout.projectDirectory.dir("dingo")

    from(project(':dingo-proxy').layout.buildDirectory) {
        include("libs/dingo-proxy-*.jar")
        exclude("libs/dingo-proxy-*-plain.jar")
    }
    into layout.projectDirectory.dir("dingo")

    from(project(':dingo-store-local').layout.buildDirectory) {
        include("libs/dingo-store-local-*-all.jar")
    }
    into layout.projectDirectory.dir("dingo")

    rename { fileName ->
        fileName.replace("-$project.version", "")
    }

}

tasks.register('packageDistribution', Zip) {
    dependsOn(copyDepends, downloadJdk)
    archiveFileName = "dingo.zip"
    destinationDirectory = layout.buildDirectory.dir('distributions')
    from layout.projectDirectory.dir("dingo")
}

copyDepends.dependsOn([
    ':dingo-driver:dingo-driver-client:fatJar',
    ':dingo-example:fatJar',
    ':dingo-web:build',
    ':dingo-proxy:build',
    ':dingo-net-netty:fatJar',
    ':dingo-executor:fatJar',
    ':dingo-store-local:fatJar'
])

packageDistribution.mustRunAfter(copyDepends)

tasks.named("build") { x ->
    x.finalizedBy("packageDistribution")
}

/**
 * do CleanUp to delete the release `dingo.zip` when run `gradlew clean`.
 */
task cleanUp(type: Delete) {
    delete layout.projectDirectory.dir("dingo")
}
tasks.clean.dependsOn(tasks.cleanUp)
