import java.util.concurrent.TimeUnit

def runRootMakefileCommand(String command, Map<String, String> env) {
  def randomSuffix = UUID.randomUUID().toString()
  File outputFile = file("${command.replace(" ", "-")}-run-output-${randomSuffix}.txt")
  def deploymentProcessBuilder = new ProcessBuilder("make", "-C", project.rootDir.path, command)
  deploymentProcessBuilder.environment().putAll(env)
  deploymentProcessBuilder.redirectOutput(outputFile)
  deploymentProcessBuilder.redirectError(outputFile)
  def deploymentProcess = deploymentProcessBuilder.start()
  def processHasTerminated = deploymentProcess.waitFor(4, TimeUnit.MINUTES)
  def output = outputFile.text
  outputFile.delete()
  if (processHasTerminated && deploymentProcess.exitValue() != 0) {
    println(output)
    throw new GradleException("Deployment failed with exitCode=${deploymentProcess.exitValue()}, output=$output")
  } else if (!processHasTerminated) {
    println(output)
    throw new GradleException("Deployment timed out")
  }
  return output
}
