/*
* 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'].trim()
String username       = inProps['username']
String password       = inProps['password']
String apiKey         = inProps['apiKey'].trim()
String buildName      = inProps['buildName']
String buildNumber    = inProps['buildNumber']
String buildStatus    = inProps['buildStatus']
String buildUser      = inProps['buildUser'].trim()
String buildComment   = inProps['buildComment']
String buildProps     = inProps['buildProps']
String buildSource    = inProps['buildSource'].trim()
String buildTarget    = inProps['buildTarget'].trim()
boolean buildArtifact = inProps['buildArtifact'].toBoolean()
boolean buildDepend   = inProps['buildDepend'].toBoolean()
boolean buildCopy     = inProps['buildCopy'].toBoolean()
boolean buildDryrun   = inProps['buildDryrun'].toBoolean()
boolean allowInsecure = (inProps['allowInsecure']?:"false").toBoolean()

ArtifactoryHelper aHelper = new ArtifactoryHelper(username, password, apiKey, allowInsecure)
String promoteUrl = aHelper.getCombinedUrl(url, "api/build/promote/${buildName}/${buildNumber}")
def formattedBuildProps = formatProperties(buildProps)
def postInfo = new JsonBuilder()
postInfo {
    status(buildStatus)
    if (buildUser) {
        ciUser(buildUser)
    }
    if (buildComment) {
        comment(buildComment)
    }
    if (formattedBuildProps) {
        properties(formattedBuildProps)
    }
    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 = aHelper.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)
}

private def formatProperties(def props) {
    def formattedProps = new JsonBuilder()
    if (props) {
        formattedProps {
            props.split('\n').each() { row ->
                if (row) {
                    def columns = row.split('=')
                    if (columns.size() != 2) {
                        throw new RuntimeException('Invalid property definition. Each line must have a single equals sign ' +
                                                   'separating the property name and its value')
                    }
                    def name = columns[0]
                    def valueArray = columns[1].split('(?<!\\\\),')
                    "$name"(valueArray)
                }
            }
        }
        return formattedProps.content
    }
    else return props
}