/**
 * 
 */
package com.platomix.userprofile.utils;

import com.platomix.userprofile.model.ShellCommond;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.regex.Pattern;

/**
 * @author wookvn
 *
 *	辅助工具类
 */
public class ShellUtils {

	final public static String SHELL_DIC = "shell/";

	/**
	 * 生成shell并执行 //	@Async("shellThreadPool")
	 * @param shellData
	 * @throws IOException
	 */
	public static void shellToCluster(ShellCommond shellData) throws IOException, InterruptedException {
		String filePath = getShellFilePath(shellData);
		File shellFile = new File(filePath);
		FileUtils.writeStringToFile(shellFile, shellData.getShellCmd(), "UTF-8");
		Runtime.getRuntime().exec("chmod 777 " + filePath);

		String commond="sh " + shellFile.getAbsolutePath();
		Process p= Runtime.getRuntime().exec(commond);
		if(shellData.getIsWait()==true){
			final InputStream is1 = p.getInputStream();
			new Thread(() -> {
				BufferedReader br = new BufferedReader(new InputStreamReader(is1));
				try{
					while(br.readLine() != null) { ; }
				}
				catch(Exception e) {
					e.printStackTrace();
				}
			}).start();
			InputStream is2 = p.getErrorStream();
			BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
			while(br2.readLine() != null){}
			int i = p.waitFor();
			System.out.println(i);
		}
	}

	/**
	 * 获取shell文件路径
	 * @param shellData
	 * @return
	 */
	private static String getShellFilePath(ShellCommond shellData){
		return 	SHELL_DIC + "to"+shellData.getIp().replace('.','_')+".sh";
	}
}
