/*
 * Copyright 2012 the original author or authors.
 *
 * 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.
 */

def wrapperUpdateTask = { name, label ->
    def wrapperTaskName = "${name}Wrapper"
    def configureWrapperTaskName = "configure${wrapperTaskName.capitalize()}"

    task "$configureWrapperTaskName" {
        doLast {
            configure(tasks."$wrapperTaskName") {
                def version = new groovy.json.JsonSlurper().parseText(new URL("https://services.gradle.org/versions/$label").text)
                if (version.empty) {
                    throw new GradleException("Cannot update wrapper to '${label}' version as there is currently no version of that label")
                }
                println "updating wrapper to $label version: $version.version (downloadUrl: $version.downloadUrl)"
                distributionUrl version.downloadUrl
            }
        }
    }

    task "${wrapperTaskName}"(type: Wrapper, dependsOn: configureWrapperTaskName) {
        group = "wrapper"
    }
}

tasks.withType(Wrapper) {
    def jvmOpts = "-Xmx1024m -Dfile.encoding=UTF-8"
    inputs.property("jvmOpts", jvmOpts)
    doLast {
        def optsEnvVar = "DEFAULT_JVM_OPTS"
        scriptFile.write scriptFile.text.replace("$optsEnvVar=\"\"", "$optsEnvVar=\"$jvmOpts\"")
        batchScript.write batchScript.text.replace("set $optsEnvVar=", "set $optsEnvVar=$jvmOpts")
    }
}
wrapperUpdateTask "nightly", "nightly"
wrapperUpdateTask "rc", "release-candidate"
wrapperUpdateTask "current", "current"

if (useIncomingDistributions) {
    task incomingDistributionsWrapper(type: Wrapper) {
        distributionUrl = incomingAllDistribution.toURI().toURL()
        group = 'wrapper'
        distributionBase = Wrapper.PathBase.PROJECT
        archiveBase = Wrapper.PathBase.PROJECT
    }
}

