package api.common.util;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.InetAddress;

/**
 * 对本地系统进行操作
 */
@Slf4j
public class OsUtil {
    @SneakyThrows
    public static void exec(String command) {
        String result;
        log.info("执行命令：{}", command);
        Runtime run = Runtime.getRuntime();
        Process process = run.exec(command);
        InputStream in = new BufferedInputStream(process.getInputStream());
        StringBuilder out = new StringBuilder();
        byte[] b = new byte[8192];
        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        in.close();
        process.destroy();
        result = out.toString();
        log.info("执行结果为：{}", result.replace(File.separator, ""));
    }

    @SneakyThrows
    public static String getHostName() {
        final String hostName = InetAddress.getLocalHost().getHostName();
        log.info("本地系统主机名为：{}", hostName);
        return hostName;
    }

    @SneakyThrows
    public static String getIp() {
        return InetAddress.getLocalHost().getHostAddress();
    }


    public static void kill(String command) {
        exec("echo kill $(ps -ef | grep '" + command + "' | awk '{ print $2 }')");
    }

//    @SneakyThrows
//    public static String execute(String command) {
//        String result;
//        log.info("开始执行 linux 命令：" + command);
//        Runtime run = Runtime.getRuntime();
//        Process process = run.exec(command);
//        InputStream in = new BufferedInputStream(process.getInputStream());
//        StringBuilder out = new StringBuilder();
//        byte[] b = new byte[8192];
//        for (int n; (n = in.read(b)) != -1; ) {
//            out.append(new String(b, 0, n));
//        }
//        in.close();
//        process.destroy();
//        result = out.toString();
//        log.info("执行结果为：" + result);
//        return result;
//    }
//
//    /**
//     * 指定工作目录执行目录
//     *
//     * @param command   命令
//     * @param directory 工作目录
//     * @return 执行结果
//     */
//    @SneakyThrows
//    public static String execute(String command, String directory) {
//        String result;
//        log.info("执行本地操作系统命令：{}", command);
//        Runtime run = Runtime.getRuntime();
//        Process process = run.exec(command, null, new File(directory));
//        InputStream in = new BufferedInputStream(process.getInputStream());
//        StringBuilder out = new StringBuilder();
//        byte[] b = new byte[8192];
//        for (int n; (n = in.read(b)) != -1; ) {
//            out.append(new String(b, 0, n));
//        }
//        in.close();
//        process.destroy();
//        result = out.toString();
//        log.info("执行结果为：{}", result);
//        return result;
//    }


}
