#!/usr/bin/env groovy
/*******************************************************************************
* Licensed Materials - Property of IBM
* (c) Copyright IBM Corporation 2013. All Rights Reserved.
*
* Note to U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule
* Contract with IBM Corp.
*******************************************************************************/

import com.ibm.ram.cli.*
import com.ibm.ram.internal.cli.command.*

final def workDir = new File('.').canonicalFile

final def inputPropsFile = new File(args[0])
final def props = new Properties()
final def outputProps = new Properties()
final def inputPropsStream = null
try {
	inputPropsStream = new FileInputStream(inputPropsFile)
	props.load(inputPropsStream)
}
catch (IOException e) {
	throw new RuntimeException(e)
}

def status = props['status']
final def REPO_PATH_SEPARATOR = File.separator
def repoUrl = props['repositoryUrl']
while (repoUrl.endsWith(REPO_PATH_SEPARATOR)) {
	repoUrl = repoUrl.substring(0, repoUrl.length() - 1)
}
def username = props['username']
def password = props['password']
//def appName = props['appName']
def envName = props['envName']
//def applicationProcessRequestId = props['applicationProcessRequestId']
def guid = props['guid']
def version = props['version'] 
def baseDirectory = workDir

println "status = ${status}"
println "repoUrl = ${repoUrl}"
println "username = ${username}" 
//println "appName = ${appName}"
println "envName = ${envName}"
println "guid = ${guid}"
println "version = ${version}"

if (guid == null || guid.trim().length() == 0) {
	throw new RuntimeException("Asset guid is empty.")
}

if (version == null || version.trim().length() == 0) {
	throw new RuntimeException("Asset version is empty.")
}
//println "applicationProcessRequestId = ${applicationProcessRequestId}"

// Create the library server configuration file
String[] arguments = [ "config", "-url", repoUrl, "-u", username, "-p", password ]
println "Config Arguments = ${arguments}"
ConfigCommand cmd = new ConfigCommand(arguments)
int exitVal = Ram.execute(cmd)

// Set the tested category on the environment asset
if (exitVal == 0) {
	// Environment asset id and version
	//def environmentGuid = "${appName}_${envName}"
	//def environmentVersion = applicationProcessRequestId

	// Set the tested category on the environment asset
	arguments = [ "set", guid, version , "-c", "Continuous Delivery/Deployment History/${envName}/Tested/${status}"]
	println "Set Arguments = ${arguments}"
	SetCommand setCommand = new SetCommand(arguments)
	exitVal = Ram.execute(setCommand)
}

System.exit(exitVal)
