/*
* 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 javax.servlet.http.*

import com.urbancode.air.plugin.artifactory.ArtifactoryHelper
import com.urbancode.commons.util.IO
import com.urbancode.air.AirPluginTool

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()

def isEmpty(value) {
    return value == null || value.equals("")
}

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

final def REPO_PATH_SEPARATOR = "/"

def repoName = props['repositoryName']
def artifacts = props['artifacts'].split('\n')
def username = props['username']
def password = props['password']
def apiKey = props['apiKey'].trim()
def checkHash = props['checkHash']
def repoUrl = props['artifactoryUrl']
boolean allowInsecure = Boolean.valueOf(props['allowInsecure'])

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

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

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

try {
    artifacts.each { artifact ->
        //remove trailing slashes from artifact
        while (artifact.endsWith(REPO_PATH_SEPARATOR)) {
            artifact = artifact.substring(0, artifact.length() - 1)
        }
        String[] attrs = artifact.split('/')
        String repoKey = ""
        for (int i = 0; i <= attrs.length - 2; ++i) {
            repoKey = repoKey + attrs[i] + REPO_PATH_SEPARATOR
        }

        String packageName = attrs[attrs.length - 1]
        if (!(packageName =~ /(?i)\.nupkg$/)) {
            packageName = packageName + ".nupkg"
        }

        String artifactUri = repoUrl + REPO_PATH_SEPARATOR + 'api/storage/' + repoKey + packageName
        File artifactFile = aHelper.downloadFileFromRepo(artifactUri, checkHash.toString())
        if (artifactFile == null) {
            throw new Exception("[Error] Failed to download artifact : " + artifact)
        }

        //copy the temp file to this directory with the file name
        File finalFile = new File(workDir, packageName)
        println ("[Action] Moving downloaded artifact to: ${finalFile.getAbsolutePath()}")
        try {
            IO.move(artifactFile, finalFile)
        }
        catch (IOException ex) {
            println ("[Error] Could not move downloaded artifact: ${ex.getMessage()}")
            exitVal=1
        }
        artifactFile.delete()
    }
}
catch (Exception e) {
    e.printStackTrace()
    exitVal=1
}
System.exit(exitVal)
