import com.ibm.urbancode.zos.common.DeploymentConstants;
import com.ibm.urbancode.zos.common.DeploymentHelper;
import com.ibm.urbancode.zos.common.PackageManifestXMLHelper
import com.urbancode.air.AirPluginTool
import com.ibm.urbancode.zos.jes.passticket.PassTicketUtil;

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


try {

	def apTool = new AirPluginTool(this.args[0], this.args[1])
	final def workDir = new File('.').canonicalFile
	def props = apTool.getStepProperties();
	final def inputPropsFile = new File(args[0]);

	final def versionName 	= DeploymentHelper.getStringInput(props['versionName']);
	def repositoryType = DeploymentHelper.getStringInput(props['repositoryType']);
	if ("CODESTATION".equalsIgnoreCase(repositoryType)) {
		println("Version ${versionName} is stored in CodeStation. Use Download Artifacts for zOS step to retrieve the version.");
		println("FTP failed.");
		System.exit(1);
	}

	final def componentName = DeploymentHelper.getStringInput(props['componentName']);
	final def repositoryPath= DeploymentHelper.getStringInput(props['basePath']);
	final def hostName 		= DeploymentHelper.getStringInput(props['hostName']);
	final def userid 		= DeploymentHelper.getStringInput(props['userid']);
	final def password 		= DeploymentHelper.getStringInput(props['password']);
	final def resourceId   	= DeploymentHelper.getStringInput(props['resourceId']);
	final def usePassticket = Boolean.valueOf(props['usePassticket']?.trim());
	final def irrracfLibraryPath 	= props['irrracfLibraryPath']?.trim();
	final def applID 		= DeploymentHelper.getStringInput(props['applID']);
	
	DeploymentHelper.inputNotEmptyCheck(hostName,"Host name should not be empty")

	if(!password || password.length() < 1){
		if(usePassticket){
			println "Password is empty. Using PassTicket authentication."
			userid = userid.toUpperCase();
			password = PassTicketUtil.generatePassTicket(userid,applID,irrracfLibraryPath);
		}else{
			throw new IllegalArgumentException("Password can not be empty.");
		}
	}
	
	def directoryOffset = DeploymentHelper.getStringInput(props['directoryOffset']);
	def workingDirectory = workDir;
	if (directoryOffset) {
		workingDirectory = new File(workDir, directoryOffset).canonicalFile;
	}

	final def workingDirComponentPath 	= workingDirectory.canonicalPath;
	def packageFilePath 				= DeploymentHelper.getFilePathInWorkingDir(workingDirComponentPath, versionName, resourceId, DeploymentConstants.PACKAGE_FILE_NAME);
	def packageManifestFilePath 		= DeploymentHelper.getFilePathInWorkingDir(workingDirComponentPath, versionName, resourceId, DeploymentConstants.PACKAGE_MANIFEST_FILE_NAME);

	//Do some clean up action to avoid dirty data
	final def workingdirVersionPath = DeploymentHelper.getVersionDirPathInWorkingDir(workingDirComponentPath, versionName, resourceId);
	DeploymentHelper.cleanWorkDir(workingdirVersionPath);

	final def repoPathInFtpServer 	=  DeploymentHelper.getVersionDirPathInRepository(repositoryPath, componentName, versionName);

	println "FTP Host name is $hostName";
	def ant = new AntBuilder();
	ant.ftp( server:"$hostName",
	userid:"$userid",
	password:"$password",
	passive:"yes",
	verbose:"true",
	action:"get",
	remotedir:"$repoPathInFtpServer",
	binary:"yes" ) {
		fileset( dir:"${workingdirVersionPath}" ) {
			include( name:"${DeploymentConstants.PACKAGE_FILE_NAME}" );
			include( name:"${DeploymentConstants.PACKAGE_MANIFEST_FILE_NAME}" );
		}
	}

	//Verify the ftp result to make sure the ftp step success
	DeploymentHelper.verifyGetArtifectResult(packageManifestFilePath,
		"Error getting ${DeploymentConstants.PACKAGE_MANIFEST_FILE_NAME}:${repoPathInFtpServer}/${DeploymentConstants.PACKAGE_MANIFEST_FILE_NAME} does not exist in the repository");
	
	def packageManifestHelper = new PackageManifestXMLHelper();
	if (packageManifestHelper.isGenericOnlyVersion(packageManifestFilePath)) {
		apTool.setOutputProperty("genericonly", "true");
	} else {
		apTool.setOutputProperty("genericonly", "false");
		DeploymentHelper.verifyGetArtifectResult(packageFilePath,
			"Error getting ${DeploymentConstants.PACKAGE_FILE_NAME}:${repoPathInFtpServer}/${DeploymentConstants.PACKAGE_FILE_NAME} does not exist in the repository");
	}
	
	apTool.storeOutputProperties()
} catch (Exception e) {
	println "Error getting package: ${e.message}";
	e.printStackTrace();
	System.exit(1);
}

System.exit(0);