/*
* 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

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 buildStatus   = props['buildStatus'].trim()

final def repositoryUrl = props['repositoryUrl'] ? props['repositoryUrl'].trim() : ""
final def branch        = props['branch'] ? props['branch'].trim() : ""
final def commitId      = props['commitId'] ? props['commitId'].trim() : ""

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

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

println "Build Status: $buildStatus"
println "Repository URL: $repositoryUrl"
println "Branch: $branch"
println "Commiit ID: $commitId"
println ""

try {

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

    if (!dra.publishBuild(buildStatus, repositoryUrl, branch, commitId)) {
        println "[Error] Publish Build failed. Review error output for details."
        System.exit(1)
    }
} finally {
    if (dra) {
        dra.closeClient()
    }
}
