/*
* 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'].trim()
String password    = inProps['password']
String apiKey      = inProps['apiKey'].trim()
String buildName   = inProps['buildName']
String buildNumber = inProps['buildNumber']
String buildStatus = inProps['buildStatus']
String buildRepos  = inProps['buildRepos']
String buildType   = inProps['buildType']

// validation
if (buildNumber && buildStatus) {
    println ('[Error] Cannot have both Build Number and Build Status specified, only one or the other.')
    println ('[Possible Solution] Please update the step configuration to have either only Build Number or only Build Status.')
    System.exit(1)
}
def reposArray = []
reposArray = buildRepos.split(',')*.trim()

final def workDir = new File('.').canonicalFile

ArtifactoryHelper aHelper = new ArtifactoryHelper(username, password, apiKey)
String retrieveUrl = aHelper.getCombinedUrl(url, 'api/archive/buildArtifacts')
JsonBuilder postInfo = new JsonBuilder()
postInfo {
    delegate.buildName(buildName)
    delegate.buildNumber(buildNumber)
    archiveType(buildType)
    if (buildStatus) {
        delegate.buildStatus(buildStatus)
    }
    if (reposArray) {
        repos(reposArray)
    }
}

String fileName = "${buildName}-${buildNumber}-buildarchive.${buildType}"
println ("[Action]  Downloading build ${buildName} #${buildNumber} to ${fileName}")
boolean downloaded = aHelper.downloadArchive(retrieveUrl, postInfo.toString(), "${buildType}", fileName, workDir)
if (!downloaded) {
    println ("[Error]  Could not download build archive.")
    System.exit(1)
}
else {
    System.exit(0)
}