/*
 * 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.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
def automation = stepProps['automation']
final String repoUrl = stepProps['automation/url']
final String username = stepProps['automation/user']
final String password = stepProps['automation/password'] ?: stepProps['automation/passScript']

final def repoName = stepProps['repositoryName']
final def targetPath = stepProps['targetPath'];
final def baseDir = stepProps['baseDir']
final def fileName = stepProps['fileName']

final String artifactPropsStr = stepProps['artifactProps']
final Properties artifactProps = new Properties()
if (artifactPropsStr) {
    artifactProps.load(new StringReader(artifactPropsStr))
}

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

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

ArtifactoryHelper helper = new ArtifactoryHelper(username, password);

File uploadDir = new File(workDir, baseDir);

println("Uploading all files matching \"$fileName\" in directory \"$uploadDir.path\"");
helper.uploadFileToRepo(repoUrl, repoName, targetPath, uploadDir, fileName, artifactProps);

apTool.setOutputProperty("buildlife/artifactory.versionId", targetPath)
apTool.setOutputProperty("buildlife/artifact.repository.prop.sheet.${automation}", automation)
apTool.storeOutputProperties()
