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

// Create a uniquely named directory
File createUniqueDirectory(File baseDir, String baseName) {
	File result = null
	int count = 0
	while (result == null) {
		String name = baseName + count + ".package"
		File file = new File(baseDir, name)
		if (!file.exists()) {
			file.mkdirs()
			result = file
		}
		count++
	}
	return result
}

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 community = props['community']
def guid = props['guid']
def version = props['version']
def appName = props['appName']
def envName = props['envName']
def applicationProcessRequestId = props['applicationProcessRequestId']

def baseDirectory = workDir

println "repoUrl = ${repoUrl}"
println "username = ${username}"
println "community = ${community}"
println "guid = ${guid}"
println "version = ${version}"
println "appName = ${appName}"
println "envName = ${envName}"
println "applicationProcessRequestId = ${applicationProcessRequestId}"

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

if (exitVal == 0) {
	// Get the environment id an version
	def environmentVersion=applicationProcessRequestId
	def environmentGuid="${appName}_${envName}"

	BufferedWriter bw = null
	try {

		// Create a unique folder for the environment package
		File packageDir = createUniqueDirectory(workDir, "env_package")

		// Create a package.json in the environment package folder
		File descriptor = new File(packageDir, "package.json")
		descriptor.createNewFile()
		FileWriter fw = new FileWriter(descriptor.getAbsoluteFile())
		bw = new BufferedWriter(fw)

		// Write the package.json contents
		bw.write("{\n\"id\":\"${environmentGuid}\",\n\"version\":\"${environmentVersion}\",\n\"type\":\"Environment\",\n\"dependencies\":[{\"id\":\"${guid}\",\"version\":\"${version}\"}]\n}")
		bw.flush()
		bw.close()
		bw = null

		// Publish the asset
		arguments = [ "publish", packageDir.getAbsoluteFile()]
		println "Publish Arguments = ${arguments}"
		PublishCommand publishCommand = new PublishCommand(arguments)
		exitVal = Ram.execute(publishCommand);
	}
	catch (Exception e) {
		if (bw != null) {
			bw.flush()
			bw.close()
		}
		e.printStackTrace()
		exitVal = 1
	}
}

System.exit(exitVal)
