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

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

	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 likeDatasetName = props['likeDatasetName'].trim();
	def volumeSerial = props['volumeSerial'].trim();
	def spaceUnit = props['spaceUnit'].trim();
	def primaryQuantity = Integer.valueOf(props['primaryQuantity'].trim());
	def secondaryQuantity = Integer.valueOf(props['secondaryQuantity'].trim());

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

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

	// generate command

	def cmd = "alloc da(${datasetName}) like(${likeDatasetName}) "
	
	if(primaryQuantity>0 && secondaryQuantity>0){
		cmd += "space(${primaryQuantity},${secondaryQuantity}) "
		if(spaceUnit == "TRACKS" || spaceUnit == "CYLINDERS"){
			cmd += spaceUnit
		}
	}
	
	if(volumeSerial && volumeSerial.length() >0){
		cmd += " VOLUME(${volumeSerial})"
	}

	println "Executing TSO command: ${cmd}"
	def tsoHelper = new TSOHelper()
	tsoHelper.runCommandFromUSS(cmd);
	
	if (tsoHelper.returnCode > 0) {
		println "Failed to allocate data set." 
		println tsoHelper.outputText
		println tsoHelper.errorText
	}else{
		println "Data set allocated."
	}
	
	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);
}