#!/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)
}

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 srcguid = props['srcguid']
def srcversion = props['srcversion']
def targetguid = props['targetguid']
def targetversion = props['targetversion']
def relationshipType = props['relationshipType']
 

def baseDirectory = workDir

println "repoUrl = ${repoUrl}"
println "username = ${username}" 
println "source guid = ${srcguid}"
println "source version = ${srcversion}"
println "target guid = ${targetguid}"
println "target version = ${targetversion}"
println "relationship type = ${relationshipType}"

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

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

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

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

if (relationshipType == null || relationshipType.trim().length() == 0) {
	throw new RuntimeException("Relationship type is empty.")
}

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

// Add the relationship between two assets
if (exitVal == 0) {
	def target = "${relationshipType}:${targetguid}:${targetversion}"; 
	 
	arguments = [ "set", srcguid, srcversion , "-r", target ]
	println "Set Arguments = ${arguments}"
	SetCommand setCommand = new SetCommand(arguments)
	exitVal = Ram.execute(setCommand)
} 

System.exit(exitVal)