/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2014, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

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 = Boolean.valueOf(inProps['allowInsecure'])

String proxyHost = inProps['proxyHost']?.trim()
String proxyPort = inProps['proxyPort']?.trim()
String proxyPass = inProps['proxyPass']?.trim()
String proxyUser = inProps['proxyUser']?.trim()

ArtifactoryHelper aHelper = new ArtifactoryHelper(username, password, apiKey, allowInsecure, proxyHost, proxyPort, proxyPass, proxyUser)
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
}