#!/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 java.io.BufferedReader
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.io.InputStreamReader

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

// Download a list of assets
int downloadAssets(packageList, includeDependent, directory){
	List<String> args = new ArrayList<String>();
	args.add("get")
	args.add("-l");
	args.add(packageList)
	args.add("-d")
	args.add(directory)
	
	// -n : do not download dependent assets
	if ((includeDependent == null) || (Boolean.valueOf(includeDependent) == Boolean.FALSE)) {
		args.add("-n")
	} 

	String[] getArgs = args.toArray(new String[args.size()]);
	println "Get Arguments = ${getArgs}"
	GetCommand getCmd = new GetCommand(getArgs)
	return Ram.execute(getCmd)
}

// Return a string representing an asset to download.
// The format of the asset string must be:
//  id/version or
//  id/ramSearch(queryString)
//
String getString(asset) {
	String aString
	
	int firstSlash = asset.toString().indexOf('/');
	if (firstSlash == -1) {
		println "Asset syntax is not valid: ${asset}"
		System.exit(1)
	}
	
	String guid = asset.toString().substring(0, firstSlash).trim();
	String searchCriteria = asset.toString().substring(firstSlash+1).trim();
	
	if (guid == null || guid.length() == 0 || searchCriteria == null || searchCriteria.length() == 0) {
		println "Asset syntax is not valid: ${asset}"
		System.exit(1)
	}
		
	if (searchCriteria.toLowerCase().startsWith("ramsearch")) {
		aString = "{ \"id\":\"${guid}\",\"query\":\"${searchCriteria}\"}"
	} else {
		aString = "{ \"id\":\"${guid}\",\"version\":\"${searchCriteria}\"}"
	}
	return aString
}

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
String 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 assets = props['assets'].split('\n')
def includeDependent = props['includeDependent']
def community = props['community']
def directoryOffset = props['directoryOffset']
 

// 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 "assets = ${assets}"
println "includeDependent = ${includeDependent}" 
println "community = ${community}"
println "baseDirectory = ${baseDirectory}"
 

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

if (exitVal == 0) {
	BufferedWriter bw = null
	try {
		// Create a json file that contains a list of assets to get
		File descriptor = File.createTempFile("packages-", ".json")
		FileWriter fw = new FileWriter(descriptor.getAbsoluteFile())
		bw = new BufferedWriter(fw)

		// Read asset list and store in temp file
		bw.write("{\n\"packages\" : [")
		for (int i = 0; i < (assets.size()-1); i++) {
			bw.write(getString(assets[i])+",\n")
		}
		bw.write(getString(assets[assets.size()-1]))
		bw.write("\n]\n}")
		bw.flush()
		bw.close()
		bw = null 

		// Get the assets
		exitVal = downloadAssets(descriptor.getCanonicalPath(), includeDependent, baseDirectory.toString())
	}
	catch (Exception e) {
		if (bw != null) {
			bw.flush()
			bw.close()
		}
		e.printStackTrace()
		exitVal = 1
	}
}

System.exit(exitVal)
