// 
// Decompiled by Procyon v0.6.0
// 

package org.jline.utils;

import java.io.OutputStream;
import java.io.InputStream;
import java.io.Closeable;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.util.Objects;

public final class ExecHelper
{
    private ExecHelper() {
    }
    
    public static String exec(final boolean redirectInput, final String... cmd) throws IOException {
        Objects.requireNonNull(cmd);
        try {
            Log.trace("Running: ", cmd);
            final ProcessBuilder pb = new ProcessBuilder(cmd);
            if (OSUtils.IS_AIX) {
                final Map<String, String> env = pb.environment();
                env.put("PATH", "/opt/freeware/bin:" + env.get("PATH"));
                env.put("LANG", "C");
                env.put("LC_ALL", "C");
            }
            if (redirectInput) {
                pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
            }
            final Process p = pb.start();
            String result = waitAndCapture(p);
            Log.trace("Result: ", result);
            if (p.exitValue() != 0) {
                if (result.endsWith("\n")) {
                    result = result.substring(0, result.length() - 1);
                }
                throw new IOException("Error executing '" + String.join(" ", (CharSequence[])cmd) + "': " + result);
            }
            return result;
        }
        catch (final InterruptedException e) {
            throw (IOException)new InterruptedIOException("Command interrupted").initCause(e);
        }
    }
    
    public static String waitAndCapture(final Process p) throws IOException, InterruptedException {
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        InputStream in = null;
        InputStream err = null;
        OutputStream out = null;
        try {
            in = p.getInputStream();
            int c;
            while ((c = in.read()) != -1) {
                bout.write(c);
            }
            err = p.getErrorStream();
            while ((c = err.read()) != -1) {
                bout.write(c);
            }
            out = p.getOutputStream();
            p.waitFor();
        }
        finally {
            close(in, out, err);
        }
        return bout.toString();
    }
    
    private static void close(final Closeable... closeables) {
        for (final Closeable c : closeables) {
            if (c != null) {
                try {
                    c.close();
                }
                catch (final Exception ex) {}
            }
        }
    }
}
