/*
* 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.AirPluginTool
import com.urbancode.ubuild.codestation.client.AuthenticationCredentials
import com.urbancode.ubuild.codestation.client.BuildLife
import com.urbancode.ubuild.codestation.client.CodestationClient

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)

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

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

Properties props = apTool.getStepProperties()
String url = props['automation/url']
String user = props['automation/user']
String ucdAuthToken = props["job/ucdUserAuthToken"] ?: props["buildlife/ucdUserAuthToken"] ?: props['automation/authToken']
String ucdUserAuthToken = props['job/ucdUserAuthToken']
String password = props['automation/passScript']?.trim() ?: props['automation/password']
String artifactSet = props['artifactSet']
String componentName = props['componentName']
String versionName = props['versionName']
String description = props['versionDesc']
boolean suppressArtifactSetDir = Boolean.valueOf(props['suppressArtifactSetDir'] as String)
File 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"
        CodestationClient codestationClient = new CodestationClient(codestationBaseUrl, credentials)
        def artifactSetDownloadDir = suppressArtifactSetDir ? tmpDir : new File(tmpDir, artifactSet)

        println "Downloading artifact set '${artifactSet}' for project build life '${buildLifeId}'"
        BuildLife 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);
    }

    String 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()
    }
}
