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



try {

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

	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 port			= DeploymentHelper.getStringInput(props['port']);
	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']);
	
	final def protocol		 = DeploymentHelper.getStringInput(props['protocol']);
	final def useKeybaseAuth = Boolean.valueOf(props['useKeybaseAuth']?.trim());
	final def keyfile		 = DeploymentHelper.getStringInput(props['keyfile']);
	final def passphrase	 = DeploymentHelper.getStringInput(props['passphrase']);
	
	DeploymentHelper.inputNotEmptyCheck(hostName,"Host name should not be empty")

	if ("SFTP".equalsIgnoreCase(protocol)) {
		if (useKeybaseAuth) {
			DeploymentHelper.inputNotEmptyCheck(keyfile,"Location of keyfile should not be empty.");
			DeploymentHelper.inputNotEmptyCheck(passphrase,"Passphrase for private key should not be empty.")
		} else {
			DeploymentHelper.inputNotEmptyCheck(password,"Password can not be empty.")
		}
        if(!port || port.length() < 1) {
            port = "22";
        }
	} else {
		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.");
			}
		}
        if(!port || port.length() < 1) {
            port = "21";
        }
	}
	
	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 or SFTP Host name is $hostName";
	def ant = new AntBuilder();
	if ("SFTP".equalsIgnoreCase(protocol)) {
		if (useKeybaseAuth) {
			def hostPackageFile = "${userid}@${hostName}:${repoPathInFtpServer}/${DeploymentConstants.PACKAGE_FILE_NAME}";
			def hostPackageManifestFile = "${userid}@${hostName}:${repoPathInFtpServer}/${DeploymentConstants.PACKAGE_MANIFEST_FILE_NAME}";
			ant.scp(
				trust:"true",
				sftp: true,
				file: "${hostPackageFile}",
				todir:"${workingdirVersionPath}",
				keyfile: "${keyfile}",
				passphrase: "${passphrase}",
				verbose:true,
				port:"${port}" );
			ant.scp(
				trust:"true",
				sftp: true,
				file: "${hostPackageManifestFile}",
				todir:"${workingdirVersionPath}",
				keyfile: "${keyfile}",
				passphrase: "${passphrase}",
				verbose:true,
				port:"${port}" );
		} else {
			ant.scp(
				trust:"true",
				sftp: true,
				todir:"${workingdirVersionPath}",
				password:"${password}",
				file: "${hostPackageFile}",
				verbose:true,
				port:"${port}" );
			ant.scp(
				trust:"true",
				sftp: true,
				password:"${password}",
				todir:"${workingdirVersionPath}",
				file: "${hostPackageManifestFile}",
				verbose:true,
				port:"${port}" );
		}
	} else {
		ant.ftp( server:"$hostName",
			userid:"$userid",
			password:"$password",
			passive:"yes",
			verbose:"true",
			action:"get",
			remotedir:"$repoPathInFtpServer",
			port:"${port}",
			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");
		
		def file = new File(packageFilePath);
		if(!file.exists()){
			println "Warning: ${packageFilePath} doesn't exist. Either the version does not have physical artifacts or there is a problem.";
		}
	}
	
	apTool.storeOutputProperties()
} catch (Exception e) {
	println "Error getting package: ${e.message}";
	e.printStackTrace();
	System.exit(1);
}

System.exit(0);