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

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 repo       = inProps['repo'].trim()
String repoPath    = inProps['repoPath'].trim()
String classifier = inProps['classifier']?.trim()
String version    = inProps['version'].trim()
String extension  = inProps['extension'].trim()
boolean allowInsecure = (inProps['allowInsecure']?:"false").toBoolean()

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

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

ArtifactoryHelper aHelper = new ArtifactoryHelper(username, password, apiKey, allowInsecure, proxyHost, proxyPort, proxyPass, proxyUser)

String[] pathArray = repoPath.split('/')
If (pathArray.size() != 2) {
    println("[Error] Repo path '$repoPath' must use the form 'groupId/artifactId'
    System.exit(1)
}
else {
    String groupId = pathArray[0]
    String artifactId = pathArray[1]
}

// build path to artifact of form http://localhost:8080/artifactory/repo/gro/up/id/artifactid/version/artifactId-version-classifier.extension
String artifactUrl = aHelper.getCombinedUrl(url, repo)
artifactUrl = aHelper.getCombinedUrl(artifactUrl, groupId.replace('.', '/'))
artifactUrl = aHelper.getCombinedUrl(artifactUrl, artifactId)
artifactUrl = aHelper.getCombinedUrl(artifactUrl, version)
if (classifier) {
    artifactUrl = aHelper.getCombinedUrl(artifactUrl, "${artifactId}-${version}-${classifier}.${extension}")
}
else {
    artifactUrl = aHelper.getCombinedUrl(artifactUrl, "${artifactId}-${version}.${extension}")
}
def retrieved = aHelper.download(artifactUrl, workDir)
if (!retrieved) {
    System.exit(1)
}