import java.nio.file.Paths

buildscript {
    repositories {
        mavenCentral()
        mavenLocal()
    }
    dependencies {
        classpath 'org.owasp:dependency-check-gradle:5.2.2'
    }
}

plugins {
    id 'java-library'
    id 'base'
    id 'idea'
    id 'com.github.johnrengelman.shadow' version '5.1.0'
}

//// Allows to use "--scan" option without manual interactive confirmation. So it can be used on CI.
//plugins {
//    id "com.gradle.build-scan" version "3.5"
//}

//buildScan {
//    termsOfServiceUrl = "https://gradle.com/terms-of-service"
//    termsOfServiceAgree = "yes"
//}

apply from: "$rootDir/gradle/Release.gradle"
apply from: "$rootDir/gradle/DockerSupport.gradle"

ext {
    dockerImages = [
            main   : 'src/main/docker/Dockerfile'
            //openjdk : 'src/main/docker/openjdk/Dockerfile', // disabled - no image for java 11
    ]
}

allprojects {

    apply plugin: 'org.owasp.dependencycheck'

    dependencyCheck {
        if (project.hasProperty("failOnHighCVSS") && project.getProperty("failOnHighCVSS") == 'true') {
            failBuildOnCVSS = 7
        }
        skipProjects = [ ":java:installer"]
        suppressionFile = file("$rootDir/dependency-check-suppression-file.xml")
        analyzers {
            assemblyEnabled = false
        }
    }
}

idea {
    project {
        jdkName = '11'
        languageLevel = '1.8'
        vcs = 'git'
    }
}

subprojects {
    apply plugin: 'com.github.johnrengelman.shadow'
}
clean.doFirst {
    file('temp').deleteDir()
    fileTree('lib') { include '*.jar' }.each { it.delete() }
    file('~plugins').deleteDir()
}

// TODO: Investigate why do we need to delete buildSrc/build at all
task cleanBuildSrc {
    doFirst {        
        file('buildSrc/build').deleteDir()
    }
}

clean.dependsOn(cleanBuildSrc)

task cleanJava(dependsOn: [':java:cleanSubprojects', cleanBuildSrc]) {
}

//task buildJava(dependsOn: ':java:build')
//task buildDotNet(dependsOn: ':dotnet:build')

task testJava(dependsOn: 'java:allJunitTests')

task testAll(dependsOn: [':testCpp', ':testJava'])

task generateSetQsVersionScript() {
    mustRunAfter clean
    description "Generates set_qs_version.cmd"

    doLast {
        def content = """set QS_VERSION=${project.version}"""
        file("$projectDir/bin/set_qs_version.cmd").text = content
    }
}

//build.dependsOn buildJava, buildDotNet, license, generateSetQsVersionScript
build.dependsOn generateSetQsVersionScript

def currentJvm = org.gradle.internal.jvm.Jvm.current()

private String getGitRevision() {
    def gitOutput = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = gitOutput
    }
    return gitOutput.toString().replace("\n", "")
}

/**
 * Returns difference between number of commits from repo root to current head and to a specified commit.
 * If the current HEAD is directly inherited from from the tag then returned number represents number of commits since tag.
 * Otherwise the returned value has no special meaning.
 */
private Integer getCountOfCommitsSinceTag(tag) {
    def gitOutput = new ByteArrayOutputStream()
    try {
        exec {
            commandLine 'git', 'rev-list', '--count', tag
            standardOutput = gitOutput
            errorOutput = new ByteArrayOutputStream()
        }
    } catch (Exception ignore) {
        logger.warn("WARN: Failed to find git tag: " + project.version)
        return null;
    }

    def commitsFromRootToTag = gitOutput.toString()
    gitOutput.reset()

    exec {
        commandLine 'git', 'rev-list', '--count', 'HEAD'
        standardOutput = gitOutput
    }

    def commitsFromRootToHead = gitOutput.toString()
    return Integer.parseInt(commitsFromRootToHead.replace("\n", "")) - Integer.parseInt(commitsFromRootToTag.replace("\n", ""))
}

private String getBuildTimestamp() {
    def gitOutput = new ByteArrayOutputStream()
    exec {
        workingDir project.rootDir
        commandLine 'git', 'log', '-1', '--date=iso8601', '--pretty=format:%cd'
        standardOutput = gitOutput
    }
    return gitOutput.toString()
}

ext.revision = getGitRevision()
ext.commitsAfterTag = getCountOfCommitsSinceTag(project.version) // Note: project version is expected to match existing tag name
ext.commitTimestamp = getBuildTimestamp()

println '======================================================================'
println 'Platform                 ' + platformType
println 'Current JVM              ' + currentJvm
println 'Dotnet Configuration     ' + dotnetConfiguration
println 'Platform Toolset         ' + platformToolsetVersion
println 'Project version          ' + project.version
println 'Revision                 ' + ext.revision
println 'Commits after tag:       ' + ext.commitsAfterTag
println 'Commit timestamp:        ' + ext.commitTimestamp
println 'Dxapi version:           ' + dxapiVersion
println 'Repository user:         ' + findProperty("ARTIFACTORY_USER");
println '======================================================================'
