/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (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.plugin.artifactory.ArtifactoryHelper
import com.urbancode.commons.util.IO
import com.urbancode.air.AirPluginTool

//--------------------------------------------------------------------------------------------------

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

// Integration Properties
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'].split('\n');
def checkHash = stepProps['checkHash'];

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

//--------------------------------------------------------------------------------------------------

while (repoUrl.endsWith(REPO_PATH_SEPARATOR)) {
    repoUrl = repoUrl.substring(0, repoUrl.length() - 1);
}

ArtifactoryHelper helper = new ArtifactoryHelper(username, password);

artifacts.each { artifact ->
    String filter = '';
    String[] attrs = artifact.split('/');
    if (attrs.length == 4) {
        filter = attrs[3];
    }
    String version = attrs[2];
    String artifactId = attrs[1];
    String groupId = attrs[0];
    String searchUrl = repoUrl + REPO_PATH_SEPARATOR + 'api/search/gavc?' + '&g=' + groupId +
            '&a=' + artifactId + '&v=' + version;
    if (!isEmpty(filter)) {
        searchUrl = searchUrl + '&c=' + filter;
    }
    if (!isEmpty(repoName)) {
        searchUrl = searchUrl + '&repos=' + repoName;
    }

    def artifactUris = helper.searchArtifacts(searchUrl);
    for (artifactUri in artifactUris) {
        File artifactFile = helper.downloadFileFromRepo(artifactUri, checkHash.toString());
        if (artifactFile == null) {
            throw new Exception("Failed to download artifact '" + artifact + "'");
        }
        String[] currFile = artifactUri.split(REPO_PATH_SEPARATOR);
        def filename = currFile[currFile.length - 1];
        File finalFile = new File(workDir, filename);
        println "Moving downloaded artifact to '" + finalFile.getPath() + "'";
        IO.move(artifactFile, finalFile);
        artifactFile.delete();
    }
}
