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

import groovy.json.JsonBuilder

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.artifactory.ArtifactoryHelper

// Get step properties
AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
Properties inProps = apTool.getStepProperties()

String url            = inProps['url']
String username       = inProps['username']
String password       = inProps['password']
String buildName      = inProps['buildName']
String buildNumber    = inProps['buildNumber']
String buildStatus    = inProps['buildStatus']
String buildUser      = inProps['buildUser']
String buildComment   = inProps['buildComment']
String buildSource    = inProps['buildSource']
String buildTarget    = inProps['buildTarget']
boolean buildArtifact = inProps['buildArtifact'].toBoolean()
boolean buildDepend   = inProps['buildDepend'].toBoolean()
boolean buildCopy     = inProps['buildCopy'].toBoolean()
boolean buildDryrun   = inProps['buildDryrun'].toBoolean()

ArtifactoryHelper.createClient(username, password)
String promoteUrl = ArtifactoryHelper.getCombinedUrl(url, "api/build/promote/${buildName}/${buildNumber}")
def postInfo = new JsonBuilder()
postInfo {
    status(buildStatus)
    if (buildUser) {
        ciUser(buildUser)
    }
    if (buildComment) {
        comment(buildComment)
    }
    if (buildSource) {
        sourceRepo(buildSource)
    }
    if (buildTarget) {
        targetRepo(buildTarget)
    }
    artifacts(buildArtifact)
    dependencies(buildDepend)
    copy(buildCopy)
    dryRun(buildDryrun)
}
println ("[action]  Promoting build ${buildName} #${buildNumber} to status ${buildStatus}...")
def promoted = ArtifactoryHelper.jsonPost(promoteUrl, postInfo.toString())
if (!promoted) {
    println ("[error]  Could not promote build.")
    System.exit(1)
}
else {
    if (buildDryrun) {
        println ('[ok]  Dry run completed successfully.')
    }
    else {
        println ('[ok]  Build promotion completed successfully.')
    }
    System.exit(0)
}