/*
* 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 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 groupId    = inProps['groupId'].trim()
String artifactId = inProps['artifactId'].trim()
String version    = inProps['version'].trim()
String extension  = inProps['extension'].trim()

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

ArtifactoryHelper aHelper = new ArtifactoryHelper(username, password, apiKey)

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