/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2017. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import com.urbancode.air.AirPluginTool
import com.urbancode.ubuild.plugin.dra.DRAHelper
import groovy.io.FileType
import org.apache.http.impl.client.CloseableHttpClient

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()

final def serverUrl      = props['automation/serverUrl']?.trim()
final def token          = props['automation/token']?.trim()
final def orgId          = props['automation/orgId'].trim()
final def toolchainId    = props['automation/toolchainId'].trim()

final def buildArtifact  = props['buildArtifact'].trim()
final def buildId        = props['buildId'].trim()
final def sourceDirStr   = props['sourceDir'].trim()
final def fileRegex      = props['fileRegex']?.trim()?:".*"
final def environment    = props['environment']?.trim()
final def lifecycleStage = props['lifecycleStage'].trim()

//------------------------------------------------------------------------------
// Script content
//------------------------------------------------------------------------------

// Construct an empty DRAHelper class to call helper functions
DRAHelper dra = null

println "Test Source Directory: $sourceDirStr"
println "Test File Regex: $fileRegex"
println "Environment: $environment"
println "Lifecycle Stage: $lifecycleStage"
println ""

def testFiles = []
File sourceDir = new File(sourceDirStr)
if (!sourceDir.isDirectory()) {
    println "[Error] Source Directory `$sourceDirStr` does not exist."
    System.exit(1)
}

println "Tests found..."
sourceDir.eachFileMatch(FileType.FILES, ~/${fileRegex}/) { file ->
    println file
    testFiles << file
}
println "[Info] Found ${testFiles.size()} test files."

boolean fail = false

try {

    dra = new DRAHelper(serverUrl, token, orgId, toolchainId, buildArtifact, buildId)

    testFiles.forEach { file ->
        if (!dra.publishTest(file, environment, lifecycleStage)) {
            println "[Error] Publish Test '${file.getName()}` failed. Review error output for details."
            fail = true
        }
    }
} finally {
    if (dra) {
        dra.closeClient()
    }
}

// One of the test files failed to publish
if (fail == true) {
    println "[Error] One or more tests failed to publish."
    System.exit(1)
}
