package com.ruoyi.cc.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.*;

import java.io.ByteArrayOutputStream;
import java.util.Arrays;

@Slf4j
public class ShellUtil {
    /** 整串指令 -> 输出文本；超 30s 抛异常 */
    public static String exec(String wholeCmd) throws Exception {
        // 1. 自动拆成数组，支持引号、转义
        log.info("wholeCmd:{}", wholeCmd);
        CommandLine cl = CommandLine.parse(wholeCmd);
        log.info("CommandLine: " + Arrays.toString(cl.toStrings()));

        // 2. 执行并捕获输出
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();

        Executor exec = new DefaultExecutor();
        exec.setStreamHandler(new PumpStreamHandler(out, err));
        exec.setWatchdog(new ExecuteWatchdog(30_000)); // 30s 超时
        try {
            int exit = exec.execute(cl);
            // 0 表示成功
            return out.toString("UTF-8");
        } catch (Exception e) {
            /* --- 3. 组装统一错误信息 --- */
            int exitCode = -1;
            if (e instanceof ExecuteException) {
                exitCode = ((ExecuteException) e).getExitValue();
            }
            String stdout = out.toString("UTF-8");
            String stderr = err.toString("UTF-8");

            // 把 docker 原始报错完整带出去
            String msg = String.format("Command failed (exit=%d)%nstdout:%n%s%nstderr:%n%s",
                    exitCode, stdout, stderr);
            throw new CmdExecException(exitCode, msg);
        }
    }

    /* ---------- 使用 ---------- */
    public static void main(String[] args) throws Exception {
        String cmd = "docker exec -i freeswitch-debian12 " +
                "/usr/local/freeswitchvideo/bin/hw_fingerprint -v";
        String result = exec(cmd);
        System.out.println(result);
    }
}
