/*
* 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 java.io.IOException;
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

import org.codehaus.jettison.json.JSONObject;

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 CommandHelper cmdHelper   = new CommandHelper(workDir);

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

try {
	try {
	    def userHomeDir  = new File(System.getProperty("user.home"))
	    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);
	}

    cmdHelper.ignoreExitValue(true);
    def cmdArgs = [javaFile.absolutePath, '-jar', udClientJarFile.absolutePath,
        "--weburl", url,
        "createVersion",
        "--component", componentName,
        "--name", versionName];
    
    if (ucdAuthToken) {
        cmdArgs << "--authtoken" << ucdAuthToken
    }
    else {
        cmdArgs << "--username" << user << "--password" << password
    }

    def versionId = null;
    def createVersionOutput = null
    int exitCode = cmdHelper.runCommand("Creating IBM UrbanCode Deploy Component Version", cmdArgs) { Process proc ->
        proc.out.close() // close stdin
        proc.consumeProcessErrorStream(System.out) // forward stderr
        createVersionOutput = proc.text.trim();
    };
    // Only try to parse as JSON if there was no error
    if (exitCode == 0) {
        def versionJson = new JSONObject(createVersionOutput);
        versionId = versionJson.getString("id");
    }
    if (versionId) {
        println "Created version ${versionName} on component ${componentName} with id ${versionId}"
     
        apTool.setOutputProperty("buildlife/udeploy.versionId", versionId)
        apTool.setOutputProperties()
    }
    
    cmdHelper.ignoreExitValue(false);
    cmdArgs = [javaFile.absolutePath, '-jar', udClientJarFile.absolutePath,
        "--weburl", url,
        "addVersionFiles",
        "--component", componentName,
        "--version", versionName,
        "--base", tmpDir.absolutePath,
        "--verbose"]
    
    if (ucdAuthToken) {
        cmdArgs << "--authtoken" << ucdAuthToken
    }
    else {
        cmdArgs << "--username" << user << "--password" << password
    }

    println "\nPublishing files for version ${versionName} on component ${componentName}"
    cmdHelper.runCommand("Publish IBM UrbanCode Deploy Component Version Files", cmdArgs) { proc ->
        proc.out.close() // close stdin
        proc.consumeProcessErrorStream(System.out) // forward stderr
        def commandOutput = proc.text.trim()
        println commandOutput
    }
    
    println "Success"
}
finally {
    if (tmpDir.exists()) {
        tmpDir.deleteDir()
    }
}