/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. 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.*
import com.urbancode.ubuild.codestation.client.*

import org.apache.log4j.BasicConfigurator
import org.apache.log4j.ConsoleAppender
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.PatternLayout

BasicConfigurator.resetConfiguration()
Logger.getRootLogger().setLevel(Level.ERROR)
Logger.getRootLogger().addAppender(new ConsoleAppender(new PatternLayout("%m%n")))
Logger.getLogger("com.urbancode.ubuild.codestation").setLevel(Level.DEBUG)
Logger.getLogger("com.urbancode.vfs.client").setLevel(Level.INFO)

final def javaHome = System.getenv('JAVA_HOME')
final def webUrl = System.getenv('WEB_URL')
final def authToken = System.getenv('AUTH_TOKEN')
final def buildLifeId = System.getenv('BUILD_LIFE_ID')
final def pluginHome = System.getenv("PLUGIN_HOME")

final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def workDir = new File('.').canonicalFile
final def javaFile = new File(new File(javaHome), 'bin/java' + (apTool.isWindows ? '.exe' : ''))
final def udClientJarFile = new File(new File(pluginHome), 'lib/udclient.jar')

final def props = apTool.getStepProperties()
def url = props['automation/url']
def user = props['automation/user']
def ucdAuthToken = props["job/ucdUserAuthToken"] ?: props["buildlife/ucdUserAuthToken"] ?: props['automation/authToken']
def ucdUserAuthToken = props['job/ucdUserAuthToken']
def password = props['automation/passScript']?.trim() ?: props['automation/password']
final def artifactSet = props['artifactSet']
def componentName = props['componentName']
def versionName = props['versionName']
def description = props['versionDesc']
boolean suppressArtifactSetDir = Boolean.valueOf(props['suppressArtifactSetDir'])
final def tmpDir = new File(System.getProperty("java.io.tmpdir"), "ucb-" + UUID.randomUUID().toString())

UCDBase ucd = new UCDBase()
ucd.workDir = workDir
ucd.javaFile = javaFile
ucd.udClientJarFile = udClientJarFile

ucd.url = url
ucd.user = user
ucd.password = password
if (ucdUserAuthToken) {
    ucd.ucdAuthToken = ucdUserAuthToken
}
else {
    ucd.ucdAuthToken = ucdAuthToken
}

ucd.component = componentName
ucd.version = versionName
ucd.isWindows = apTool.isWindows

try {
    try {
        def credentials = AuthenticationCredentials.createAuthTokenCredentials(authToken)
        def codestationBaseUrl = webUrl.endsWith("/") ? webUrl + "rest2" : webUrl + "/rest2"
        def codestationClient = new CodestationClient(codestationBaseUrl, credentials)
        def artifactSetDownloadDir = suppressArtifactSetDir ? tmpDir : new File(tmpDir, artifactSet)

        println "Downloading artifact set '${artifactSet}' for project build life '${buildLifeId}'"
        def buildLife = codestationClient.buildLifeLookup.findBuildLife(buildLifeId)
        codestationClient.downloadArtifacts(buildLife, artifactSet, artifactSetDownloadDir)
    }
    catch (IOException e) {
        String message = "An error occurred accessing the CodeStation Repository at ${webUrl}. It is " +
            "defined in the System - Server Settings page as the Agent External URL value. If this URL is incorrect, " +
            "please change it. Detailed error message: " + e.toString();
        throw new Exception(message, e);
    }
    catch (Exception e) {
        String message = "Error retrieving artifacts from CodeStation: " + e.toString();
        e.printStackTrace();
        throw new Exception(message, e);
    }

    def versionId = ucd.createVersion(description)
    if (versionId) {
        println "Created version ${versionName} on component ${componentName} with id ${versionId}"
        apTool.setOutputProperty("buildlife/udeploy.versionId", versionId)
        apTool.setOutputProperties()
    }

    ucd.publishFiles(tmpDir.absolutePath, null, null)
}
finally {
    if (tmpDir.exists()) {
        tmpDir.deleteDir()
    }
}
