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

package org.jline.builtins.ssh;

import java.io.Closeable;
import java.util.logging.Level;
import java.util.Map;
import java.io.IOException;
import org.apache.sshd.server.channel.ChannelSession;
import org.apache.sshd.server.Environment;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.ExitCallback;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.function.Consumer;
import java.util.logging.Logger;
import org.apache.sshd.server.command.Command;

public class ShellCommand implements Command
{
    private static final Logger LOGGER;
    private final Consumer<Ssh.ExecuteParams> execute;
    private final String command;
    private InputStream in;
    private OutputStream out;
    private OutputStream err;
    private ExitCallback callback;
    private ServerSession session;
    private Environment env;
    
    public ShellCommand(final Consumer<Ssh.ExecuteParams> execute, final String command) {
        this.execute = execute;
        this.command = command;
    }
    
    public void setInputStream(final InputStream in) {
        this.in = in;
    }
    
    public void setOutputStream(final OutputStream out) {
        this.out = out;
    }
    
    public void setErrorStream(final OutputStream err) {
        this.err = err;
    }
    
    public void setExitCallback(final ExitCallback callback) {
        this.callback = callback;
    }
    
    public void start(final ChannelSession channel, final Environment env) throws IOException {
        this.session = channel.getSession();
        this.env = env;
        new Thread(this::run).start();
    }
    
    private void run() {
        int exitStatus = 0;
        try {
            this.execute.accept(new Ssh.ExecuteParams(this.command, this.env.getEnv(), this.session, this.in, this.out, this.err));
        }
        catch (final RuntimeException e) {
            exitStatus = 1;
            ShellCommand.LOGGER.log(Level.SEVERE, "Unable to start shell", e);
            try {
                final Throwable t = (e.getCause() != null) ? e.getCause() : e;
                this.err.write(t.toString().getBytes());
                this.err.flush();
            }
            catch (final IOException ex) {}
        }
        finally {
            ShellFactoryImpl.close(this.in, this.out, this.err);
            this.callback.onExit(exitStatus);
        }
    }
    
    public void destroy(final ChannelSession channel) {
    }
    
    static {
        LOGGER = Logger.getLogger(ShellCommand.class.getName());
    }
}
