plugins {
    id "com.moowork.node" version "1.2.0"
}

def customNpmVersion = '5.7.1'

node {
    version = '8.5.0'
    npmVersion = customNpmVersion
    nodeModulesDir = projectDir
    download = true
}

def ciBuild = System.env['BuildRunner'] != null
def ciPublishBuild = ciBuild && (System.env['APPVEYOR_REPO_TAG'] == "true" || System.env['PLEXUS_BUILD_VSCODE_PUBLISH'] == "true")
def packageVersion = System.env["PLEXUS_BUILD_VSCODE_PACKAGE_VERSION"] ?: (System.env["APPVEYOR_REPO_TAG_NAME"] ?: System.env["PackageVersion"])
// NPM config settings
def npmRegistry = System.env['NPM_REGISTRY']
def npmEmail = System.env['NPM_AUTH_USER']
def npmAuth = System.env['NPM_AUTH_TOKEN']

tasks.npmSetup.dependsOn("genNpmrc")

task genNpmrc() {
    doLast {
        def content = """
# Auto generated by Gradle build
${npmRegistry != null ? "registry=" + npmRegistry : ""}
${npmEmail != null ? "email=" + npmEmail : ""}
${npmAuth != null ? "_auth=" + npmAuth : ""}
        """
        def npmConfigFolder = "$projectDir/.gradle/npm/npm-v$customNpmVersion/etc"
        file(npmConfigFolder).mkdirs()
        // global config
        file("$npmConfigFolder/npmrc").text = content
        // user config
        file("$projectDir/.npmrc").text = content
    }
}

task installServer(type: Copy) {
	dependsOn(':dsl:interop-lang.ide:installDist')
    from "../interop-lang.ide/build/install/interop-lang-server"
    into "interop-lang-server"
}

task installProtoServer(type: Copy) {
    dependsOn(':dsl:proto-lang.ide:installDist')
    from "../proto-lang.ide/build/install/proto-lang-server"
    into "proto-lang-server"
}

task npmVersion(type: NpmTask) {
    args = ['--version']
}

task npmRunInstall(type: NpmTask, dependsOn: npmVersion) {
    args = ['install']
}

tasks.npmRunInstall.dependsOn("genNpmrc")

task preNpmBuild {
    doLast {
        println "VSCode Package version: $packageVersion"
	    println "CI Publish: $ciPublishBuild"
    }
}

task npmBuild(type: NpmTask, dependsOn: ['npmRunInstall', 'installProtoServer', 'installServer', 'preNpmBuild']) {
    environment = [
        'PLEXUS_BUILD_VSCODE_PACKAGE_VERSION': packageVersion
    ]
    args = ciPublishBuild && !packageVersion.contains("-") ? ['run', 'ci-publish'] : ['run', 'build']
}

build.dependsOn npmBuild
