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

import groovy.json.JsonSlurper

import javax.servlet.http.*

import org.apache.http.HttpResponse
import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpGet
import org.apache.http.util.EntityUtils

import com.urbancode.air.plugin.artifactory.ArtifactoryHelper
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import com.urbancode.commons.util.IO

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

final def workDir = new File('.').canonicalFile
final def props = new Properties();
final def inputPropsFile = new File(args[0]);
final def inputPropsStream = null;
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

final def REPO_PATH_SEPARATOR = "/";

def repoName = props['repositoryName']
def artifacts = props['artifacts'].split('\n');
def username = props['username'];
def password = props['password'];
def checkHash = props['checkHash'];
def repoUrl = props['artifactoryUrl'];
while (repoUrl.endsWith(REPO_PATH_SEPARATOR)) {
    repoUrl = repoUrl.substring(0, repoUrl.length() - 1);
}

def exitVal = 0;
HttpClientBuilder builder = ArtifactoryHelper.getBuilder();
ArtifactoryHelper.createClient(username, password);

def searchArtifacts = { searchUrl ->
    HttpGet get = new HttpGet(searchUrl);
    HttpResponse response = ArtifactoryHelper.getClient().execute(get);
    int status = response.getStatusLine().getStatusCode();
    if (status == HttpStatus.SC_OK) {
        def artifactUris = []
        def jsonString = EntityUtils.toString(response.getEntity());
        def slurper = new JsonSlurper();
        def resultArr = slurper.parseText(jsonString).results;
        for (result in resultArr) {
            artifactUris.add(result.uri)
        }
        return artifactUris;
    }
    else {
        throw new Exception("Exception searching: " + searchUrl + "\nErrorCode : " + status.toString());
    }
}

try {
    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 = searchArtifacts(searchUrl);
        for (artifactUri in artifactUris) {
            File artifactFile = ArtifactoryHelper.downloadFileFromRepo(artifactUri, checkHash.toString());
            if (artifactFile == null) {
                throw new Exception("Failed to download artifact : " + artifact);
            }

            //copy the temp file to this directory with the file name
            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.getAbsolutePath() + "\n";
            IO.move(artifactFile, finalFile);
            artifactFile.delete();
        }
    }
}
catch (Exception e) {
    e.printStackTrace();
    exitVal=1;
}
System.exit(exitVal);
