package net.educoder.ecsonar.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;

/**
 * Created by guange on 26/02/2017.
 */
public class SystemUtil {

    private static final Logger logger = LoggerFactory.getLogger(SystemUtil.class);

    private static ExecutorService executor;

    public static class ExecuteResp{
        int status;
        String output;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getOutput() {
            return output;
        }

        public void setOutput(String output) {
            this.output = output;
        }
    }

    /**
     * 执行命令并获得输出以及退出码
     */
    public static ExecuteResp executeAndGetExitStatus(String command) {
        ExecuteResp resp = new ExecuteResp();

        logger.debug("execute: {}", command);

        StringBuffer out = new StringBuffer();
        Integer exitStatus = -1;

        ProcessBuilder pb = new ProcessBuilder(new String[]{"/bin/sh", "-c", command});
        pb.redirectErrorStream(true);
        try {
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
                out.append(System.getProperty("line.separator"));
            }
            exitStatus = process.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            logger.info("executeAndGetExitStatus: {}", command);
            logger.error("executeAndGetExitStatus: ",e);
        }

        logger.debug("out: {}", out.toString());
        resp.setOutput(out.toString().trim());
        resp.setStatus(exitStatus);

        return resp;
    }

}
