/*
* 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.*

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final def workDir = new File('.').canonicalFile
final def javaHome = System.getenv('JAVA_HOME')
final def pluginHome = System.getenv("PLUGIN_HOME")
final def webUrl = System.getenv('WEB_URL')
final def buildLifeId = System.getenv('BUILD_LIFE_ID')

final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def props = apTool.getStepProperties()

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 automation          = props['automation']
def url                 = props['automation/url']
def user                = props['automation/user']
def ucdAuthToken        = props["job/ucdUserAuthToken"] ?: props["buildlife/ucdUserAuthToken"] ?: props['automation/authToken']
def password            = props['automation/passScript'] ?: props['automation/password']
def componentName       = props['componentName']
def versionName         = props['versionName']
def statusName          = props['status']
def description         = props['versionDesc']
def includes            = props['includes']
def excludes            = props['excludes']
def publishFiles        = Boolean.valueOf(props['publishFiles'])
def artifactsBaseDir    = props['artifactsBaseDir'] ?: '.'
def propertiesTextArea  = props['propertiesTextArea']
def createVersionLink   = Boolean.valueOf(props['createVersionLink'])
def linkName            = props['linkName']
def linkUrl             = props['linkUrl']
def testPercentage      = Boolean.valueOf(props['testPercentage'])
def codeAnalytics       = Boolean.valueOf(props['codeAnalytics'])
def codeCoverage        = Boolean.valueOf(props['codeCoverage'])
def sourceChange        = Boolean.valueOf(props['sourceChange'])
def workItem            = Boolean.valueOf(props['workItem'])

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

ucd.url = url
ucd.user = user
ucd.password = password
ucd.ucdAuthToken = ucdAuthToken

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

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

    if (statusName) {
        ucd.getVersionStatuses(statusName)
        ucd.addVersionStatus(statusName)
    }

    if (publishFiles) {
        File artifactsDir = new File(workDir, artifactsBaseDir)
        ucd.publishFiles(artifactsDir.absolutePath, includes, excludes)

        apTool.setOutputProperty("buildlife/artifact.repository.prop.sheet.${automation}", automation)
        apTool.storeOutputProperties()
    }

    Properties propertiesList = new Properties()
    if (propertiesTextArea) {
        propertiesList.load(new StringReader(propertiesTextArea))
    }

    Properties properties = new BuildLifeHelper(buildLifeId).addBuildLifeMetricsProperties(testPercentage, codeAnalytics, codeCoverage, sourceChange, workItem)
    propertiesList.putAll(properties)

    if (propertiesList) {
        def httpHelper = new HttpHelper()
        httpHelper.setHttpClient(ucd.getHttpClient())
        def propsHelper = new PropsHelper(httpHelper)
        propsHelper.setComponentVersionProperties(url, componentName, versionName, propertiesList)
    }

    if (createVersionLink) {
        ucd.addVersionLink(linkName, linkUrl)
    }

}
else {
    System.exit(1)
}
