/*
 * Capture information for each executed Gradle build to display in the job summary.
 */
import org.gradle.util.GradleVersion

// Only run against root build. Do not run against included builds.
def isTopLevelBuild = gradle.getParent() == null
if (isTopLevelBuild) {
    def version = GradleVersion.current().baseVersion
    def atLeastGradle4 = version >= GradleVersion.version("4.0")
    def atLeastGradle6 = version >= GradleVersion.version("6.0")

    if (atLeastGradle6) {
        settingsEvaluated { settings ->
            if (settings.pluginManager.hasPlugin("com.gradle.enterprise")) {
                registerCallbacks(settings.extensions["gradleEnterprise"].buildScan, settings.rootProject.name)
            }
        }
    } else if (atLeastGradle4) {
        projectsEvaluated { gradle ->
            if (gradle.rootProject.pluginManager.hasPlugin("com.gradle.build-scan")) {
                registerCallbacks(gradle.rootProject.extensions["buildScan"], gradle.rootProject.name)
            }
        }
    }
}

def registerCallbacks(buildScanExtension, rootProjectName) {
    buildScanExtension.with {
        def buildFailed = false
        buildFinished { result ->
            buildFailed = (result.failure != null)
        }

        buildScanPublished { buildScan ->
            def buildResultsDir = new File(System.getenv("RUNNER_TEMP"), ".build-results")
            buildResultsDir.mkdirs()
            
            def buildResultsFile = new File(buildResultsDir, System.getenv("GITHUB_ACTION") + System.currentTimeMillis() + ".json")

            def requestedTasks = gradle.startParameter.taskNames.join(" ")
            def gradleVersion = GradleVersion.current().version
            def buildScanUri = buildScan.buildScanUri.toASCIIString()
            def buildResults = [
                rootProject: rootProjectName, 
                requestedTasks: requestedTasks,
                gradleVersion: gradleVersion, 
                buildFailed: buildFailed, 
                buildScanUri: buildScanUri
            ]
            buildResultsFile << groovy.json.JsonOutput.toJson(buildResults)

            println("::set-output name=build-scan-url::${buildScan.buildScanUri}")
        }
    }
}