plugins {
    id "com.moowork.node" version "1.2.0"
    id "com.github.hierynomus.license" version"0.14.0"
}

def ciBuild = System.env['BuildRunner'] != null
def ciPublishBuild = ciBuild && (System.env['APPVEYOR_REPO_TAG'] == "true" || System.env['NPM_PUBLISH'] == "true")
def isWindows = org.gradle.internal.os.OperatingSystem.current().isWindows()
def e2eTestsEnabled = isWindows && System.env['BuildRunner'] != "MyGet" && System.env['PLEXUS_BUILD_SKIP_WEB_TESTS'] != 'true'
def ciFullBuild = ciBuild && e2eTestsEnabled
def npmPackageVersion = System.getenv("PLEXUS_BUILD_NPM_PACKAGE_VERSION") ?: (System.getenv("APPVEYOR_REPO_TAG_NAME") ?: System.getenv("PackageVersion"))
def npmRegistry = System.env['NPM_REGISTRY']
def npmEmail = System.env['NPM_AUTH_USER']
def npmAuth = System.env['NPM_AUTH_TOKEN']
def customNpmVersion = '6.10.3'

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

license {
    header file("${rootDir}/FILE_HEADER")
    mapping {
        ts='JAVADOC_STYLE'
        proto='DOUBLESLASH_STYLE'
        interop='DOUBLESLASH_STYLE'
    }
    strictCheck true
}

task licenseFormatTS(type: com.hierynomus.gradle.license.tasks.LicenseFormat) {
    source = fileTree(dir: ".").exclude("**/node_modules/*").exclude("**/dist/*")
            .include("**/*.ts").include("**/*.js").include("**/*.proto").include("**/*.interop")
}

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
    }
}

tasks["license"].dependsOn licenseFormatTS
licenseFormat.dependsOn licenseFormatTS

tasks.npmSetup.dependsOn genNpmrc

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

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

task preNpmBuild {
    doLast {
        println "NPM Package version: $npmPackageVersion"
	    println "CI Publish: $ciPublishBuild"
	    println "CI Full: $ciFullBuild"
	    println "CI Build: $ciBuild"
	    println "Integration tests: $e2eTestsEnabled"
        File packagesDir = file('packages');
        FileCollection collection = files { packagesDir.listFiles() }
        println "\nModules to build:"
        collection.collect { relativePath(it) }.sort().each { println it }
    }
}

task npmBuild(type: NpmTask, dependsOn: ['npmRunInstall', 'preNpmBuild', ':dsl:gen:cli:build']) {
    // https://github.com/srs/gradle-node-plugin/issues/128 
    environment = [
        'PLEXUS_BUILD_NPM_PACKAGE_VERSION': npmPackageVersion,
        'PLEXUS_CLI_SKIP_JRE_DOWNLOAD': 'true',
        'PLEXUS_CLI_SKIP_PROTOC_DOWNLOAD': 'true'
    ]
    args =  ciPublishBuild ? ['run', 'ci-publish'] :
            ciFullBuild ? ['run', 'ci-build-e2e'] : 
            ciBuild ? ['run', 'ci-build'] :
            e2eTestsEnabled ? ['run', 'build-e2e'] : ['run', 'build']
}

task npmBuildOnly(type: NpmTask, dependsOn: ['npmRunInstall', 'preNpmBuild']) {
    args =  ['run', 'build']
}

task buildTransport(dependsOn: npmBuild) {
    outputs.dir('.')
}

task build(dependsOn: buildTransport) {
}

build.dependsOn('license')
