package com.chenyang.nse.bussiness.tools.command;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.qos.logback.classic.Logger;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.tools.logger.LoggerBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.net.ftp.FTPClient;

public class CommandTool {
   public static void command(String command) {
      String os = System.getProperty("os.name");
      Process process = null;

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            process = Runtime.getRuntime().exec(command);
            InputStream is = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer tv_result = new StringBuffer();

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            System.out.println("command is :" + command);
            System.out.println("command return :" + tv_result);
            is.close();
            reader.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

   }

   public static void command1(String command) {
      String os = System.getProperty("os.name");
      Process process = null;

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            process = Runtime.getRuntime().exec(command);
            InputStream is = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer tv_result = new StringBuffer();

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            is.close();
            reader.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

   }

   public static void commandRtn2(String command) {
      String os = System.getProperty("os.name");
      Process process = null;
      new StringBuffer();
      new StringBuffer();

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            process = Runtime.getRuntime().exec(command);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static void commandRtn(String command) {
      String os = System.getProperty("os.name");
      Process process = null;
      StringBuffer tv_result = new StringBuffer();
      StringBuffer tv_result2 = new StringBuffer();

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            process = Runtime.getRuntime().exec(command);
            InputStream errorStream = process.getErrorStream();
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream));

            String line2;
            while((line2 = reader2.readLine()) != null) {
               tv_result2.append(line2 + "\n");
            }

            System.out.println("command is :" + command);
            System.out.println("command return errorStream:" + tv_result);
            System.out.println("command return inputStream:" + tv_result2);
            errorStream.close();
            inputStream.close();
            reader.close();
            reader2.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

   }

   public static void commandRtnToFile(String command, String filepath) throws IOException {
      File targetFile = new File(filepath);
      if (targetFile.exists()) {
         if (targetFile.isDirectory()) {
            targetFile.createNewFile();
         }
      } else {
         File file2 = new File(targetFile.getParent());
         file2.mkdirs();
         if (!targetFile.isDirectory()) {
            file2.createNewFile();
         }
      }

      String os = System.getProperty("os.name");
      Process process = null;

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            process = Runtime.getRuntime().exec(command);
            InputStream errorStream = process.getErrorStream();
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
            OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(filepath, true), "utf-8");

            String line;
            while((line = reader.readLine()) != null) {
               output.append(line + "\n");
               output.flush();
            }

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream));

            String line2;
            while((line2 = reader2.readLine()) != null) {
               output.append(line2 + "\n");
               output.flush();
            }

            errorStream.close();
            inputStream.close();
            reader.close();
            reader2.close();
            output.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

   }

   public static String commandRtn3(String command) {
      String os = System.getProperty("os.name");
      Process process = null;
      StringBuffer tv_result = new StringBuffer();
      StringBuffer tv_result2 = new StringBuffer();

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            process = Runtime.getRuntime().exec(command);
            InputStream errorStream = process.getErrorStream();
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream));

            String line2;
            while((line2 = reader2.readLine()) != null) {
               tv_result2.append(line2 + "\n");
            }

            errorStream.close();
            inputStream.close();
            reader.close();
            reader2.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

      return tv_result2.toString();
   }

   public static String commandRtn1(String command) {
      String os = System.getProperty("os.name");
      Process process = null;
      StringBuffer tv_result = new StringBuffer();
      StringBuffer tv_result2 = new StringBuffer();

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            String[] cmds = new String[]{"/bin/sh", "-c", command};
            process = Runtime.getRuntime().exec(cmds);
            InputStream errorStream = process.getErrorStream();
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream));

            String line2;
            while((line2 = reader2.readLine()) != null) {
               tv_result2.append(line2 + "\n");
            }

            errorStream.close();
            inputStream.close();
            reader.close();
            reader2.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

      return tv_result2.toString();
   }

   public static void commandPipeRtn(String command) {
      String os = System.getProperty("os.name");
      Process process = null;
      StringBuffer tv_result = new StringBuffer();
      StringBuffer tv_result2 = new StringBuffer();

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
         } else {
            String[] cmds = new String[]{"/bin/sh", "-c", command};
            process = Runtime.getRuntime().exec(cmds);
            InputStream errorStream = process.getErrorStream();
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream));

            String line2;
            while((line2 = reader2.readLine()) != null) {
               tv_result2.append(line2 + "\n");
            }

            System.out.println("command is :" + command);
            System.out.println("command return errorStream:" + tv_result);
            System.out.println("command return inputStream:" + tv_result2);
            errorStream.close();
            inputStream.close();
            reader.close();
            reader2.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

   }

   public static List<String> remoteRunCmd(String hostname, int port, String username, String password, String cmd, String code) {
      List<String> list = new ArrayList();
      Connection conn = new Connection(hostname, port);
      Session sess = null;

      try {
         conn.connect();
         boolean isAuthenticated = conn.authenticateWithPassword(username, password);
         if (!isAuthenticated) {
            throw new IOException("Authentication failed.");
         }

         sess = conn.openSession();
         sess.execCommand(cmd);
         System.out.println("Here is some information about the remote host:");
         InputStream stdout = sess.getStdout();
         BufferedReader br = new BufferedReader(new InputStreamReader(stdout, code));

         while(true) {
            String line = br.readLine();
            if (line == null) {
               break;
            }

            list.add(line);
         }
      } catch (IOException e) {
         e.printStackTrace(System.err);
      } finally {
         sess.close();
         conn.close();
      }

      return list;
   }

   public static List<String> remoteRunCmdftp(String filename, String hostname, int port, String username, String password, int row, String delimiters, String code) {
      List<String> list = new ArrayList();
      FTPClient ftpClient = new FTPClient();

      try {
         ftpClient.connect(hostname, port);
         boolean isAuthenticated = ftpClient.login(username, password);
         if (!isAuthenticated) {
            throw new IOException("Authentication failed.");
         }

         InputStream stdout = ftpClient.retrieveFileStream(filename);
         System.out.println("Here is some information about the remote host:");
         BufferedReader br = new BufferedReader(new InputStreamReader(stdout, code));
         int count = 0;

         String content;
         for(content = ""; count < row; ++count) {
            content = br.readLine();
         }

         if (content != null) {
            list.add(String.valueOf(content.split(delimiters).length));
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            ftpClient.disconnect();
         } catch (IOException e) {
            e.printStackTrace();
         }

      }

      return list;
   }

   public static void newcommand(String command) {
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
         RandomAccessFile encryptionLog = null;
         encryptionLog = new RandomAccessFile(props.getProperty("commandpath") + "/commandlog.log", "rw");
         encryptionLog.setLength(0L);
         encryptionLog.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      String os = System.getProperty("os.name");
      Process process = null;
      String res = "";

      try {
         Logger encryptionlogger = (new LoggerBuilder()).getLogger(props.getProperty("commandpath"), "/commandlog");
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            StringBuffer tv_result = new StringBuffer();

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            res = tv_result.toString();
            reader.close();
         } else {
            process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer tv_result = new StringBuffer();

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
               encryptionlogger.info(line + "\n");
            }

            reader.close();
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static String getlogcommand(String date, Integer count) {
      LocalDate today = LocalDate.now();
      String logpath = "";
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      if (date.equals(today.toString())) {
         logpath = props.getProperty("deployPath") + "/encryption.log";
      } else {
         logpath = props.getProperty("oldlogpath") + "/system-" + date + ".log";
      }

      String command = " tail -n " + count + " " + logpath;
      String os = System.getProperty("os.name");
      Process process = null;
      String res = "";

      try {
         if (os.toLowerCase().startsWith("win")) {
            process = Runtime.getRuntime().exec("cmd /c " + command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"));
            StringBuffer tv_result = new StringBuffer();

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            res = tv_result.toString();
            reader.close();
         } else {
            process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer tv_result = new StringBuffer();

            String line;
            while((line = reader.readLine()) != null) {
               tv_result.append(line + "\n");
            }

            res = tv_result.toString();
            reader.close();
         }

         process.waitFor();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

      return res;
   }

   public static void main(String[] args) {
      try {
         ProcessBuilder pb = new ProcessBuilder(new String[0]);
         pb.command("bash", "-c", "ping 192.168.2.173 -t");
         Process process = pb.start();
         BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
         int i = 0;

         String line;
         while((line = reader.readLine()) != null) {
            System.out.println(line);
            ++i;
            if (i > 6) {
               process.destroy();
               reader.close();
            }
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

   }
}
