package com.fdkankan.common.util;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by Xiewj on 2021/1/4 0004 14:53
 */
@Slf4j
public class CmdUtils {


    /**
     * 调用算法 xx.sh 脚本
     * @param command
     */
//    public static void callshell(String command){
//        try {
//            String[] cmd = new String[]{"/bin/sh", "-c", command};
//            Process process = Runtime.getRuntime().exec(cmd);
//            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
//            errorGobbler.start();
//            StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "STDOUT");
//            outGobbler.start();
//            process.waitFor();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }



    public static void callLineSh(String command) throws Exception {
        callLineSh(command, null);

    }

    /**
     * 直接java调用命令
     * @param command
     */
    public static void callLine(String command) throws Exception {
        callLine(command, null);

    }

    /**
     * 直接java调用命令
     * @param command
     */
    public static void callLine(String command, Integer lineSize) throws Exception {
        log.info("cmd: " + command);
        Process process = Runtime.getRuntime().exec(command);
        log.info("开始运行");
        StreamGobblerLine errorGobbler = new StreamGobblerLine(process.getErrorStream(), "ERROR");
        errorGobbler.start();
        // 200行打印一次日志
        StreamGobblerLine outGobbler = new StreamGobblerLine(process.getInputStream(), "STDOUT", lineSize);
        outGobbler.start();
        process.waitFor();
    }

    /**
     *
     * @param command 命令
     * @param lineSize 日志输出行数 ，可以为null
     */
    public static void callLineSh(String command, Integer lineSize) throws Exception {
        log.info("cmd: " + command);
        String[] cmd = new String[]{"/bin/sh", "-c", command};
        Process process = Runtime.getRuntime().exec(cmd);
        log.info("开始运行");
        StreamGobblerLine errorGobbler = new StreamGobblerLine(process.getErrorStream(), "ERROR");
        errorGobbler.start();
        // 200行打印一次日志
        StreamGobblerLine outGobbler = new StreamGobblerLine(process.getInputStream(), "STDOUT", lineSize);
        outGobbler.start();
        process.waitFor();
    }

    /**
     * 调用sh脚本上传oss
     */
//    public static void ossUploadDir(String sceneCode, String uploadDir, String target){
//
//        String cmd = CmdConstant.OSSUTIL_UPLOAD_DIR;
//        cmd = cmd.replaceAll("@sceneCode", sceneCode);
//        cmd = cmd.replaceAll("@uploadDir", uploadDir);
//        cmd = cmd.replaceAll("@target", target);
//
//        log.info("ossCmd: " + cmd);
//        long start = System.currentTimeMillis();
//        CmdUtils.callLineSh(cmd);
//        long end = System.currentTimeMillis();
//        log.info("场景码目录：{} 上传完成, 耗时：{} s" , sceneCode, (end-start)/1000 );
//    }



}
