import org.apache.tools.ant.taskdefs.condition.Os

plugins {
    id "com.github.hierynomus.license" version"0.14.0"
    id "de.undercouch.download" version "3.2.0"
}

repositories {
    mavenCentral()
}

def dotnetSdkVersion = "5.0"
def buildCache = System.getenv("PLEXUS_BUILD_CACHE_DIR") ?: new File("${rootDir}/build").absolutePath
def coreOnly = System.env['PLEXUS_BUILD_CORE_ONLY'] == 'true'
def net4Only = System.env['PLEXUS_BUILD_NET4_ONLY'] == 'true'
def nugetPublish = System.env['PLEXUS_BUILD_NUGET_PUBLISH'] == 'true'
def testsEnabled = Os.isFamily(Os.FAMILY_WINDOWS) && System.env['BuildRunner'] != "MyGet" && System.env['PLEXUS_BUILD_SKIP_DOTNET_TESTS'] != 'true'
def nugetVersion = System.getenv("PLEXUS_BUILD_NUGET_VERSION") ?: System.getenv("APPVEYOR_REPO_TAG_NAME")
def dotnetParams = nugetVersion == null ? " " : "/p:Version=$nugetVersion"

if (net4Only) {
    dotnetParams += " /p:NET4_ONLY=true"
} else if (coreOnly) {
    dotnetParams += " /p:CORE_ONLY=true"
}

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

task licenseFormatCS(type: com.hierynomus.gradle.license.tasks.LicenseFormat) {
    source = fileTree(dir: 'src').exclude("**/bin/*").exclude("**/obj/*")
            .exclude("**/google/protobuf/*.proto")
            .include("**/*.cs").include("**/*.proto").include("**/*.interop")
}

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

task prepareDotnet {
    doLast {

        println "Only netcore: $coreOnly"
        println "Only net4: $net4Only"
        println "Tests enabled: $testsEnabled"

        def dotnetVersion = new ByteArrayOutputStream()
        exec {
            ignoreExitValue true
            commandLine 'cmd', '/c', "$projectDir/dotnet.cmd", "--version"
            standardOutput = dotnetVersion;
        }
        dotnetVersion = "$dotnetVersion".trim()

        if (dotnetVersion.startsWith(dotnetSdkVersion)) {
            println "Dotnet SDK $dotnetSdkVersion is already installed, skipping downloading"
        } else {
            println "Dotnet SDK $dotnetSdkVersion is not installed on the current machine. 'dotnet --version' command output: '$dotnetVersion'. Downloading Dotnet SDK $dotnetSdkVersion to $buildCache."

            download {
                onlyIfNewer true
                src 'https://download.visualstudio.microsoft.com/download/pr/57776397-c87d-4eb8-9080-d58d180ccbe6/920afd9e178bdcd10fcfe696c1fdb88c/dotnet-sdk-5.0.408-win-x64.zip'
                dest "$buildCache/win/sdk/dotnet.zip"
            }

            copy {
                from zipTree("$buildCache/win/sdk/dotnet.zip")
                into "$buildCache/win/sdk/dotnet"
            }

            tasks.withType(Exec) {
                environment "PATH", "$buildCache/win/sdk/dotnet/"
                environment "PLEXUS_BUILD_DOTNET_DIR", "$buildCache/win/sdk/dotnet/"
	        }
        }
    }
}

task compile(type:Exec) {
    dependsOn 'license' 
    dependsOn prepareDotnet
    
    workingDir projectDir
    environment "PLEXUS_BUILD_DOTNET_PARAMS", dotnetParams
    commandLine "$projectDir/build.cmd"
}

if (testsEnabled) {
    task test(dependsOn: compile, type:Exec) {
        dependsOn prepareDotnet
        workingDir projectDir
    	ignoreExitValue false
        environment "PLEXUS_BUILD_DOTNET_PARAMS", dotnetParams
        commandLine "$projectDir/tests.cmd"
    }
} else {
    task test(dependsOn: compile) {
        doLast {
            println "Skipping tests because current platform is not Windows or running in MyGet"
        }
    }
}

if (nugetVersion != null && nugetPublish) {
    task push(dependsOn: test, type:Exec) {
        dependsOn prepareDotnet
        workingDir projectDir
        commandLine "$projectDir/push.cmd"
    }    
} else {
   task push(dependsOn: test) {
        doLast {
            println "Skipping push because nuget version is not specified, or publish disabled"
        }
    }
}

task clean {
    delete fileTree(dir: 'src').include("**/bin/*").include("**/obj/*")
}

task build (dependsOn: [compile, test, push]) {}