/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
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
	def apTool = new AirPluginTool(this.args[0], this.args[1])
	def props = apTool.getStepProperties();

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