package io.renren.common.utils;

import java.io.*;

public class JavaShellUtil {
    public static String execute(String command) {
        StringBuilder result = new StringBuilder();

        Process process = null;
        BufferedReader bufrIn = null;
        BufferedReader bufrError = null;
        try {
            process = Runtime.getRuntime().exec(command);
            process.waitFor();
            //获取执行结果
            bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
            String line = null;
            while ((line = bufrIn.readLine()) != null) {
                result.append(line).append('\n');
            }
            while ((line = bufrError.readLine()) != null) {
                result.append(line).append('\n');
            }

        } catch (Exception e) {
            return "fail";
        } finally {
            closeStream(bufrIn);
            closeStream(bufrError);
            // 销毁子进程
            if (process != null) {
                process.destroy();
            }
        }
        return result.toString().replaceAll("\\\\x", "%");
    }


    public static void createShell(String path, String... strings) throws IOException {
        File sh = new File(path);
        System.out.println(sh.getAbsolutePath());
        boolean createResult = sh.createNewFile();
        if (!sh.exists() && !createResult) {
            System.out.println("create failed");
            return;
        }
        boolean executeResult = sh.setExecutable(true);
        if (!executeResult) {
            System.out.println("execute failed");
            return;
        }
        FileWriter fw = new FileWriter(sh);
        BufferedWriter bf = new BufferedWriter(fw);

        for (int i = 0; i < strings.length; i++) {
            bf.write(strings[i]);
            if (i < strings.length - 1) {
                bf.newLine();
            }
        }
        bf.flush();
        bf.close();
    }

    public static void generate(String unformattedShell, String[] args, String path) {
        String formatShell = String.format(unformattedShell, args);
        try {
            createShell(path, formatShell);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                System.out.println("关闭连接失败");
            }
        }
    }

}
