/*
* 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.air.plugin.automation.*
import groovy.json.JsonSlurper

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final def workDir = new File('.').canonicalFile
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 stepProps = apTool.getStepProperties()
final def CommandHelper cmdHelper = new CommandHelper(workDir)

final def javaFile = new File(new File(javaHome), 'bin/java' + (apTool.isWindows ? '.exe' : ''))
final def udClientJarFile = new File(new File(pluginHome), 'lib/udclient.jar')

def url = stepProps['automation/url']
def user = stepProps['automation/user']
def ucdAuthToken = stepProps['automation/authToken']
def password = stepProps['automation/passScript'] ?: stepProps['automation/password']
def componentName = stepProps['componentName']
def versionName = stepProps['versionName']
def statusName = stepProps['status']

def cmdArgs = [javaFile.absolutePath, '-jar', udClientJarFile.absolutePath,
               "--weburl", url,
               "getStatuses",
               "--type", "version"
              ]

if (ucdAuthToken) {
    cmdArgs << "--authtoken" << ucdAuthToken
}
else {
    cmdArgs << "--username" << user << "--password" << password
}

def addVersionCommand = [javaFile.absolutePath, '-jar', udClientJarFile.absolutePath,
                         "--weburl", url,
                         "addVersionStatus",
                         "--component", componentName,
                         "--version", versionName,
                         "--status", statusName
                        ]
if (ucdAuthToken) {
    addVersionCommand << "--authtoken" << ucdAuthToken
}
else {
    addVersionCommand << "--username" << user << "--password" << password
}

def statusOutput
def statusList
cmdHelper.ignoreExitValue(true)
int exitCode = cmdHelper.runCommand("Getting the list of version statuses", cmdArgs) { proc ->
    proc.out.close() // close stdin
    proc.consumeProcessErrorStream(System.out) // forward stderr
    statusOutput = proc.text.trim()
}
cmdHelper.ignoreExitValue(false)

// Only try to parse as JSON if there was no error
if (exitCode == 0) {
    statusList = new JsonSlurper().parseText(statusOutput).name
    if (!statusList) {
        println "No statuses were found on the IBM UrbanCode Deploy server."
        System.exit(1)
    }
    
    if (!statusList.contains(statusName)) {
        println "The status '${statusName}' does not exist on the IBM UrbanCode Deploy server. Valid statuses: ${statusList}"
        System.exit(1);
    }
    
    cmdHelper.runCommand("Adding status '${statusName}' to version '${versionName}' on component '${componentName}'", addVersionCommand)
}
else {
    println "Could not get any status information from IBM UrbanCode Deploy. Trying to add the status to the version anyway."
    try {
        cmdHelper.runCommand("Adding status '${statusName}' to version '${versionName}' on component '${componentName}'", addVersionCommand)
    }
    catch (Exception e) {
        println "Failed to assign status ''${statusName}' to version '${versionName}' on component '${componentName}'. " +
                "This is typically caused by using a status that does not exist."
        System.exit(1);
    }
}