/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Build
 * IBM UrbanCode Deploy
 * IBM UrbanCode Release
 * IBM AnthillPro
 * (c) Copyright IBM Corporation 2002, 2014. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */
import org.codehaus.jettison.json.JSONArray
import org.codehaus.jettison.json.JSONObject

import com.ibm.urbancode.zos.common.DeploymentHelper;
import com.urbancode.air.AirPluginTool
import com.urbancode.ud.client.EnvironmentClient

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

	final def resourceId      =  DeploymentHelper.getStringInput(props['resourceId']);
	final def applicationName =  DeploymentHelper.getStringInput(props['applicationName']);
	final def environmentName =  DeploymentHelper.getStringInput(props['environmentName']);
	final def componentName   =  DeploymentHelper.getStringInput(props['componentName']);
	final def isDryRun 		  =  DeploymentHelper.getBooleanInput(props['isDryRun']);
	final def deployBasePath  =  DeploymentHelper.getStringInput(props['deployBasePath']);

	DeploymentHelper.inputNotEmptyCheck(applicationName, "Application name is empty.");
	DeploymentHelper.inputNotEmptyCheck(environmentName, "Environment name is empty.");
	DeploymentHelper.inputNotEmptyCheck(componentName, "Component name is empty.");
	DeploymentHelper.inputNotEmptyCheck(deployBasePath, "Deploy base path is empty.");

	//Initialize the EnvironmentClient help class and pass the auth.
	def apTool = new AirPluginTool(this.args[0], this.args[1]);
	def udUser = apTool.getAuthTokenUsername();
	def udPass = apTool.getAuthToken();
	def weburl = System.getenv("AH_WEB_URL");
	EnvironmentClient envClient = new EnvironmentClient(new URI(weburl), udUser, udPass);
	com.urbancode.air.XTrustProvider.install();

	JSONArray versions = envClient.deleteRedundantVersions(environmentName, applicationName, componentName, !isDryRun);
	def length = versions.length();
	println "Application:${applicationName}";
	println "Environment:${environmentName}";
	println "Component:${componentName}";
	
	if (length > 0) { 
		if (isDryRun) {
			println "Versions to be removed:"
			for(int i=0; i<length; i++) {
				JSONObject version = versions.getJSONObject(i);
				if (null != version && version.has("name")) {
					def versionName = version.getString("name")?.trim();
					if (null != versionName && versionName.length()>0) {
						println versionName;
					}
				}
			}
		} else {
			def pathContainsVersions = DeploymentHelper.getComponentPathInDeployBasePath(deployBasePath, resourceId, componentName, true);
			for(int i=0; i<length; i++) {
				JSONObject version = versions.getJSONObject(i);
				if(null!=version && version.has("name")) {
					def versionName = version.getString("name")?.trim();
					if (null != versionName && versionName.length()>0) {
						println "Removed version:" + versionName;
						def versionPathToDel = new File(pathContainsVersions + File.separator + versionName);
						if (versionPathToDel.isDirectory()) {
							DeploymentHelper.cleanBackUpData(versionPathToDel.getCanonicalPath());
						}
					}
				}
			}
		}
	} else {
		println "No redundant versions to remove."
	}
}
catch (Exception e) {
	println "Error remove redundant versions: ${e.message}";
	e.printStackTrace();
	System.exit(1);
}

System.exit(0);