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

final def REPO_PATH_SEPARATOR = "/"

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

//remove trailing slashes from url
while (url.endsWith(REPO_PATH_SEPARATOR)) {
    url = url.substring(0, url.length() - 1)
}

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

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 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}"
if (buildNumber && !buildStatus) {
    println ("[Action] Downloading build ${buildName} #${buildNumber} to ${fileName}")
}
else if (!buildNumber && buildStatus) {
    println ("[Action] Downloading build ${buildName} #${buildStatus} 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)
}