/*
 * 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()

// 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 includes = stepProps['includes']
final def excludes = stepProps['excludes']
final Boolean preserveDirs = stepProps['preserveDirs'].toBoolean()

final def includesList = new ArrayList<String>()
final def excludesList = new ArrayList<String>()
includes.eachLine { it ->
    File includeFile = new File(workDir, it)
    includesList << includeFile.getPath()
}
excludes.eachLine { it ->
    File excludeFile = new File(workDir, it)
    excludesList << excludeFile.getPath()
}

ArtifactoryHelper helper = new ArtifactoryHelper(username, password);

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

//--------------------------------------------------------------------------------------------------
println "Repository name: $repoName"
println "Target path: $targetPath"
println "Include patterns: $includes"
println "Exclude patterns: $excludes"
println "Preserve directories: $preserveDirs"
println "\n\n"

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

CloseableHttpClient client = helper.createClient()
try {

    String existingTargetPath = stepProps["buildlife/artifactory.target.path"]
    if (existingTargetPath != null && !existingTargetPath.equals(targetPath)) {
        throw new Exception("A previous step has uploaded artifacts to target path '" +
            existingTargetPath + "' however this step's target path is different: '" + targetPath +
            "'. Uploading artifacts to multiple different base target paths as part of the same " +
            "build life is disabled.")
    }

    helper.uploadFileToRepo(client, repoUrl, repoName, targetPath, workDir,
                            includesList, excludesList, preserveDirs, artifactProps);
    apTool.setOutputProperty("buildlife/artifactory.repository.name", repoName)
    apTool.setOutputProperty("buildlife/artifactory.target.path", targetPath)
    apTool.setOutputProperty("buildlife/artifact.repository.prop.sheet.${automation}", automation)
    apTool.storeOutputProperties()
}
finally {
    client.close()
}
