String[] runArgs(List<String> prefix, List<String> args) {
    return [
            *prefix,
            "-Dcorda.sgx.enclave.path=/code/sgx-jvm/remote-attestation/enclave/build",
            "-Djava.library.path=/code/sgx-jvm/remote-attestation/host/native/build",
            "-Dattestation.home=/code/sgx-jvm/remote-attestation/host/build/logs",
            "-Dfile.encoding=US-ASCII", "-Duser.country=US", "-Duser.language=en", "-Duser.variant",
            "-cp", sourceSets.main.runtimeClasspath.collect { it.toString() }.join(":"),
            "$debugArgs", *args
    ]
}

String[] containerArgs(String project, String... args) {
    return [
            "bash", "$projectDir/../../tools/sx/sx", "build",
            "remote-attestation/$project", *args
    ]
}

def execWait(String[] command, String directory, String ready) {
    ProcessBuilder builder = new ProcessBuilder(command)
    builder.redirectErrorStream(true)
    builder.directory(new File(directory))
    Process process = builder.start()

    if (ready == null) {
        process.waitFor()
        return
    }

    InputStream stdout = process.getInputStream()
    BufferedReader reader = new BufferedReader(new
            InputStreamReader(stdout))

    def line
    while ((line = reader.readLine()) != null) {
        println line
        if (line.contains(ready)) {
            println "Command $command is ready"
            break
        }
    }

    stdout.close()
}

def containerDebugWait(String directory, String project, String... args) {
    def ready = "Listening for transport dt_socket at address:"
    execWait(containerArgs(project, args), directory, ready)
}

/*
 * R3 Proprietary and Confidential
 *
 * Copyright (c) 2018 R3 Limited.  All rights reserved.
 *
 * The intellectual and technical concepts contained herein are proprietary to R3 and its suppliers and are protected by trade secret law.
 *
 * Distribution of this file or any portion thereof via any medium without the express permission of R3 is strictly prohibited.
 */

ext {
    runArgs = this.&runArgs
    containerArgs = this.&containerArgs
    containerDebugWait = this.&containerDebugWait
}