/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.exec;

import com.jcraft.jsch.ChannelExec;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.util.IOUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class SshExecution implements ProcessExecution {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(SshExecution.class);
    private final ChannelExec channel;

    public SshExecution(ChannelExec channel) {
        this.channel = channel;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return channel.getInputStream();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return channel.getOutputStream();
    }

    @Override
    public InputStream getErrorStream() throws IOException {
        return channel.getErrStream();
    }

    @Override
    public String drainInput(Charset set) throws IOException {
        return IOUtil.readAll(channel.getInputStream(), set);
    }

    @Override
    public String drainInput() throws IOException {
        return drainInput(Charset.defaultCharset());
    }

    /**
     * Close the handle and release any associated resources. Close always succeeds even if the underlying
     * resource is in an error condition.
     */
    @Override
    public void close() {
        logger.info("Closing execution channel.");
        channel.disconnect();
    }

    public int getReturnCode() {
        return channel.getExitStatus();
    }
}
