/*
* 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 com.ibm.urbancode.zos.common.TSOHelper;
import com.urbancode.air.AirPluginTool;

try{
	def apTool = new AirPluginTool(this.args[0], this.args[1])

/* Here we call getStepProperties() to get a Properties object that contains the step properties
 * provided by the user. 
 */
	def props = apTool.getStepProperties();

	//set up working directory
	def workDir = new File(".").canonicalFile;
	def pluginHome = System.getenv("PLUGIN_HOME");
	def dirOffset = props['dirOffset'];

	def datasetName=props['datasetName'].trim();
	def managementClass = props['managementClass'].trim();
	def storageClass = props['storageClass'].trim();
	def dataClass = props['dataClass'];

	if(!datasetName || datasetName.length() < 1){
		throw new IllegalArgumentException("Data set name can not be empty.");
	}

	if (!managementClass && !storageClass && !dataClass){
		throw new IllegalArgumentException("At least one class needs to be specified.");
	}


	// generate command
	def cmd = "ALLOCATE DATASET(${datasetName}) NEW "
	
	if (managementClass){
		cmd += "MGMTCLAS(${managementClass}) "
	}
	if (storageClass){
		cmd += "STORCLAS(${storageClass}) "
	}
	if (dataClass){
		cmd += "DATACLAS(${dataClass}) "
	}
	
	println cmd
	
	/* issue command */
	def tsoHelper = new TSOHelper()
	tsoHelper.runCommandFromUSS(cmd);
	
	if (tsoHelper.returnCode > 0) {
		println tsoHelper.errorText;
	}
	println tsoHelper.outputText
	
	//Set an output property
	apTool.setOutputProperty("returnCode", tsoHelper.returnCode.toString());
	
	apTool.storeOutputProperties();//write the output properties to the file
}catch (Exception e) {
		println "Error allocating data set: ${e.message}";
		e.printStackTrace();
		System.exit(1);
}