/*
 * 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 buildInfoJson = stepProps['buildInfoJson']

ArtifactoryHelper helper = new ArtifactoryHelper(username, password);

//--------------------------------------------------------------------------------------------------
println "Build info JSON file: $buildInfoJson"
println "\n\n"

//--------------------------------------------------------------------------------------------------
File buildInfoFile = new File(workDir, buildInfoJson)
if (!buildInfoFile.exists()) {
    throw new Exception("Build info json file does not exist: $buildInfoFile")
}

String buildInfoJsonContent = buildInfoFile.getText("UTF-8")

CloseableHttpClient client = helper.createClient()
try {
    println "Uploading build information to $repoUrl"
    helper.uploadBuildInfoJson(client, repoUrl, buildInfoJsonContent);
}
finally {
    client.close()
}
