/*
* 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
*/
package com.ibm.urbancode.zos.common

public class RexxHelper {
    def script
    def output
    def error
    def codePage
    def file

    int runRexx() {
        def process = file.getAbsolutePath().execute();
        def out = new StringBuilder()
        def err = new StringBuilder()
        process.waitForProcessOutput(out, err);
        if (out) this.output = "out:\n$out"
        if (err) this.error = "err:\n$err"
        def returnCode = process.exitValue();
        if (returnCode == 0) {
            output += "The rexx script is executed successfully."
        } else {
            output = "$output\n program terminated with return code $returnCode \n"
            error = "$error\n Rexx script is:\n $script"
        }
        //clean up temp files
        file.deleteOnExit()
        return returnCode
    }

    def generateRexxScript(script) {
        file = File.createTempFile("script", ".rexx");
        file.write(this.script, this.codePage);
        file.setExecutable(true);
    }

    def execute() {
        this.generateRexxScript(this.script)
        return this.runRexx()
    }

    def execute(script, codePage = "cp037") {
        this.script = script
        this.codePage = codePage
        return this.execute()
    }
}
