package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class ShellCmd {


    public static boolean runCommand(String cmd) {
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            int status = process.waitFor();
            String msg = readMsg(process);
            if (status == 0) {
                log.info("Success  cmd " + cmd + " status:" + status + "\r\n" + msg);
                return true;
            } else {
                log.error("Failed  cmd " + cmd + " status:" + status + "\r\n" + msg);
                return false;
            }
        } catch (Exception e) {
            log.error("Exception  cmd " + cmd + "\r\n" + e.getMessage());
        }
        return false;
    }


    public static String readMsg(Process process) {
        BufferedReader input = null;
        StringBuffer buffer = new StringBuffer();
        try {
            input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";

            while ((line = input.readLine()) != null) {
                buffer.append(line).append("\r\n");
            }
            return buffer.toString();
        } catch (Exception e) {
            log.error(null,e);
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                log.error(null,e);
            }
        }
        return "";
    }
}
