/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2017. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import com.urbancode.air.AirPluginTool;
import com.ibm.rational.air.plugin.worklight.Util;
import com.ibm.rational.air.plugin.worklight.V8Util;

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

def serverpath = props['serverpath']
def runtime = props['runtime']
def adapters = Util.text2List(props['adapter'])
def worklightAntJar = props['worklightAntJar'].trim()
def user = props['user']
def password = props['password']
boolean secure = Boolean.parseBoolean(props['secure']?: "true")

try {
    println "Deploying the Worklight adapter with the following properties:"
    println "Server Path: ${serverpath}"
    println "Adapter(s): ${adapters}"
    println "Worklight Ant Deployer JAR Path: ${worklightAntJar}"
    println ""

    // Confirm all given files exists
    for (adapter in adapters) {
        File adapterFile = new File(adapter)
        def fileName = adapterFile.getName()
        if (!adapterFile.isFile()) {
            println "Error: The Worklight adapter file name given does not exist. " +
                "Please enter a valid file path and name: ${fileName}."
            System.exit(-1)
        }
        int extension = fileName.lastIndexOf(".")
        if(extension == -1 || fileName.substring(extension) != ".adapter") {
            println "Error: The Worklight adapter file name must include the .adapter " +
                "extension: ${adapterFile.getName()}. For example, file.adapter."
            System.exit(-1)
        }
    }
    File worklightAntJarFile
    if (worklightAntJar) {
        worklightAntJarFile = new File(worklightAntJar)
        if(!worklightAntJarFile.exists() || !worklightAntJarFile.isFile() ||
            !Util.isWorklightDeployerAntJar(worklightAntJarFile)) {
            println "Error: The path to the Worklight Ant Deployer JAR file is invalid: " +
                    "${worklightAntJarFile.getCanonicalPath()}. Change the value of the " +
                    "Worklight Ant JAR File Path attribute to the path to the Worklight " +
                    "Ant Deployer JAR file. For example, use " +
                    "/opt/IBM/Worklight/WorklightServer/worklight-ant-deployer.jar."
            System.exit(-1)
        }
    } else {
        println "[Info] The Worklight Jar is not specified. Connecting to MobileFirst v8 using the REST client."
    }

    def serverVersion = Util.determineServerVersion(worklightAntJarFile, serverpath, user, password, secure);
    for (adapter in adapters) {
        if(serverVersion == Util.WL_SERVER_60 || serverVersion == Util.WL_SERVER_61) {
            def ant = new AntBuilder();
            try {
                ant.taskdef ( name: "deployer",
                    classname:"com.worklight.ant.deployers.AdapterDeployerTask",
                    classpath: worklightAntJarFile.absolutePath )
            } catch (Exception e) {
                println "Error: The class com.worklight.ant.deployers.AdapterDeployerTask is " +
                        "not found in the specified Worklight Ant Deployer JAR file: " +
                        "${worklightAntJarFile.getCanonicalPath()}."
                println "Explanation: This error occurs if the JAR file specified in the " +
                        "Worklight Ant JAR File Path attribute is not correct."
                println "User response: Change the value of the Worklight Ant JAR File Path " +
                        "attribute to the path to the Worklight Ant Deployer JAR file. For " +
                        "example, use " +
                        "/opt/IBM/Worklight/WorklightServer/worklight-ant-deployer.jar."
                System.exit(-1)
            }
            if(user?.trim()) {
                if(password?.trim()) {
                    ant.deployer ( worklightServerHost:serverpath, deployable:adapter,
                        userName:user, password:password )
                }
                else {
                    println "Error: A password must be provided for the user."
                    System.exit(-1)
                }
            } else {
                ant.deployer ( worklightServerHost:serverpath, deployable:adapter )
            }
        } else if ( serverVersion == Util.WL_SERVER_62  ||
                    serverVersion == Util.WL_SERVER_63  ||
                    serverVersion == Util.WL_SERVER_70  ||
                    serverVersion == Util.WL_SERVER_71
                ) {

            def ant = Util.getWLADMAnt(worklightAntJarFile);
            ant.wladm ( url:serverpath, user:user, password:password, secure:secure) {
                'deploy-adapter' ( runtime:runtime, file:adapter )
            }
        } else if ( serverVersion == Util.WL_SERVER_80 ) {
            new V8Util(serverpath,user,password).postAdapter(runtime, adapter, "false", null)
        } else {
            if(serverVersion) {
                println "Error: The Worklight Server version is not supported.";
            } else {
                println "Error: The Worklight Server version could not be determined or there " +
                    "is a mismatch between the Worklight Ant Deployer JAR and the server.";
                println "Explanation: This error can occur if the Worklight Server Path specified " +
                    "in the Server Path attribute is not correct or the path to the Worklight Ant " +
                    "Deployer JAR specified in the Worklight Ant JAR File Path attribute is not " +
                    "correct.";
                println "User response: Verify the path specified by the Server Path attribute is " +
                    "correct. For example, use http://localhost:9080/worklight on Worklight " +
                    "6.0 or 6.1 Servers, or https://localhost:9443/worklightadmin on Worklight " +
                    "6.2 Servers. Verify the JAR file specified in the Worklight Ant JAR File " +
                    "Path attribute uses the JAR from the corresponding Worklight Server. For " +
                    "example, use /opt/IBM/Worklight/WorklightServer/worklight-ant-deployer.jar.";
            }
            System.exit(-1)
        }
    }
} catch (Exception e) {
    println "An error occurred while deploying the Worklight adapter: ${e.message}";
    e.printStackTrace();
    System.exit(-1);
}

println "The Deploy Adapter to Worklight Server step completed successfully."
System.exit(0)
