#!/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.client.RAMAsset;
import com.ibm.ram.client.RAMSession;
import com.ibm.ram.common.data.AssetIdentification;
import com.ibm.ram.common.data.Relationship;
import com.ibm.ram.internal.cli.command.*

def List<Relationship> filterRelationships(relationships, relationshipTypes) {
	List<Relationship> list= new ArrayList<Relationship>();
	if (relationshipTypes != null && relationshipTypes.length >0) {
		for (String relationshipType : relationshipTypes) { 
			for (Relationship relationship : relationships) { 
				if (relationshipType.equals(relationship.getRelationshipTypeName())) {
					list.add(relationship); 
				}
			}
		}
	} else {
		if (relationships != null && relationships.length >0)
			list.addAll(Arrays.asList(relationships));
	}
	return list
} 

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 directoryOffset = props['directoryOffset']
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['relationshipTypes']
 

// Get the working directory
def baseDirectory = workDir
try {
	if (directoryOffset) {
		baseDirectory = new File(workDir, directoryOffset).canonicalFile
	}
}
catch (Exception e) {
	throw new RuntimeException(e)
}

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.")
}

def relationshipTypes = null;
if (relationshipType != null && relationshipType.trim().length() >  0) {
	relationshipTypes = relationshipType.split (",")
	
}

// 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)
String[] getArgs;
GetCommand getCmd
if (exitVal == 0) {
	RAMSession ramSession = null;
	try {
		 ramSession = new RAMSession(repoUrl, username, password)
		AssetIdentification assetIdentification = new AssetIdentification(srcguid, srcversion)
		RAMAsset asset = ramSession.getAsset(assetIdentification);
		Relationship[] relationships = asset.getRelationships();
		if (relationships != null && relationships.length >0) {
			List filteredRelationships = filterRelationships(relationships, relationshipTypes)
			if (filteredRelationships != null) {
				targetguid = (targetguid == null) ? "" : targetguid.trim()
				targetversion = (targetversion == null) ? "" : targetversion.trim()
				
				for (Relationship rel : filteredRelationships) {
					String childGuid = rel.getChildAssetGUID();
					String childVersion = rel.getChildAssetVersion();
					
					
					if ( targetguid.length() ==0 || targetguid.equals(childGuid)
						&& ( targetversion.length() ==0 || targetversion.equals(childVersion))) { 
						getArgs = [ "get", childGuid, childVersion, "-d", baseDirectory.toString() ] 
						println("Get Arguments = " + getArgs)
						 
						getCmd = new GetCommand(getArgs)
						exitVal = Ram.execute(getCmd)
						 
						if (exitVal != 0) {
							break;
						}
					}
				}
				 
			}
		}
	} finally {
		ramSession.release();
	}
	
} 
 

System.exit(exitVal)