/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 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.plugin.artifactory.ArtifactoryHelper
import com.urbancode.air.AirPluginTool
import org.apache.http.impl.client.CloseableHttpClient

//--------------------------------------------------------------------------------------------------
final def workDir = new File('.').canonicalFile
final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def stepProps = apTool.getStepProperties()

final String repoUrl = stepProps['automation/url']
final String username = stepProps['automation/user']
final String password = stepProps['automation/password'] ?: stepProps['automation/passScript']

def repoName = stepProps['repositoryName']
def artifacts = stepProps['artifacts']
def verifyHash = stepProps['checkHash'].toBoolean()

ArtifactoryHelper helper = new ArtifactoryHelper(username, password)

//--------------------------------------------------------------------------------------------------
repoUrl = helper.trimTrailingSlashes(repoUrl)
repoName = helper.trimLeadingSlashes(repoName)
repoName = helper.trimTrailingSlashes(repoName)

//--------------------------------------------------------------------------------------------------
println "Repository name: $repoName"
println "Artifacts to download:"
artifacts.eachLine { line ->
    line = helper.trimLeadingSlashes(line)
    println "   $line"
}
println "Verify hash: $verifyHash"
println "\n\n"

//--------------------------------------------------------------------------------------------------
CloseableHttpClient client = helper.createClient()
try {
    artifacts.eachLine { targetPath ->
        targetPath = helper.trimLeadingSlashes(targetPath)
        String url = repoUrl + "/" + repoName + "/" + targetPath
        println "Downloading $url"

        File artifactFile = helper.downloadFileFromRepo(client, repoUrl, repoName, workDir, targetPath, verifyHash)
        if (artifactFile == null) {
            throw new Exception("Failed to download artifact '" + artifact + "'")
        }
        println "Downloaded $url to $artifactFile.path"
    }
}
finally {
    client.close()
}