/**
* Licensed Materials - Property of IBM* and/or HCL**
* IBM UrbanCode Deploy
* (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.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 user = props['user']
def password = props['password']
def runtime = props['runtime']
def application = props['application']
def environment = props['environment']
def version = props['version']
def archive = props['archive']

try {
    println "Deploying the web resource with the following properties:"
    println "Server Path: ${serverpath}"
    println "Runtime: ${runtime}"
    println "Application ID: ${application}"
    println "Environment: ${environment}"
    println "Version: ${version}"
    println "Archive: ${archive}"
    println()

    if (!new File(archive).isFile()) {
        println "Error: The MobileFirst web resource archive file name given does not exist. " +
        "Please enter a valid file path and name: ${archive}."
        System.exit(-1)
    }

    def serverVersion = Util.determineServerVersion(null, serverpath, user, password, false)

    if (!serverVersion) {
        println "Error: The MobileFirst Server version could not be determined."
        println "Explanation: This error can occur if the value specified " +
            "for the Server Path property is not correct."
        println "User response: Verify the value specified for the Server Path property is " +
            "correct. For example, https://localhost:8443/mfpadmin"
        System.exit(-1)
    }

    if (serverVersion != Util.WL_SERVER_80) {
        println "Error: The MobileFirst Server version is not supported by this step."
        System.exit(-1)
    }

    new V8Util(serverpath,user,password).postWebResource(runtime, application, environment, version, archive)
} catch (Exception e) {
    println "An error occurred while deploying the web resource: ${e.message}"
    System.exit(-1)
}

println "The Deploy Web Resource step completed successfully."
System.exit(0)
