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

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()
    }
}
