/*
 * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package io.github.bonigarcia.wdm;

import static java.lang.String.join;
import static java.lang.invoke.MethodHandles.lookup;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.slf4j.LoggerFactory.getLogger;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;

/**
 * Command line executor.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 3.0.0
 */
public class Shell {

    static final Logger log = getLogger(lookup().lookupClass());

    private Shell() {
        throw new IllegalStateException("Utility class");
    }

    public static String runAndWait(String... command) {
        return runAndWaitArray(new File("."), command);
    }

    public static String runAndWait(File folder, String... command) {
        return runAndWaitArray(folder, command);
    }

    public static String runAndWaitArray(File folder, String[] command) {
        String commandStr = Arrays.toString(command);
        log.debug("Running command on the shell: {}", commandStr);
        String result = runAndWaitNoLog(folder, command);
        log.debug("Result: {}", result);
        return result;
    }

    public static String runAndWaitNoLog(File folder, String... command) {
        String output = "";
        try {
            Process process = new ProcessBuilder(command).directory(folder)
                    .redirectErrorStream(false).start();
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                handleShellException(e, command);
            }
            output = IOUtils.toString(process.getInputStream(), UTF_8);
        } catch (IOException e) {
            handleShellException(e, command);
        }
        return output.trim();
    }

    private static void handleShellException(Exception e, String... command) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "There was a problem executing command <{}> on the shell: {}",
                    join(" ", command), e.getMessage());
        }
    }

    public static String getVersionFromWmicOutput(String output) {
        int i = output.indexOf('=');
        int j = output.indexOf('.');
        return i != -1 && j != -1 ? output.substring(i + 1, j) : output;
    }

    public static String getVersionFromPosixOutput(String output,
            String driverType) {
        // Special case: using Chromium as Chrome
        if (output.contains("Chromium")) {
            driverType = "Chromium";
        }
        int i = output.indexOf(driverType);
        int j = output.indexOf('.');
        return i != -1 && j != -1
                ? output.substring(i + driverType.length(), j).trim()
                : output;
    }

    public static String getVersionFromPowerShellOutput(String output) {
        int i = output.indexOf("Version");
        int j = output.indexOf(':', i);
        int k = output.indexOf('.', j);
        return i != -1 && j != -1 && k != -1 ? output.substring(j + 1, k).trim()
                : output;
    }

}

@@ -903,37 +903,8 @@
 e;%0D%0A
-import java.io.IOException;%0D%0A
 impo
@@ -2124,31 +2124,8 @@
 );%0D%0A
-            try %7B%0D%0A    
     
@@ -2156,122 +2156,8 @@
 );%0D%0A
-            %7D catch (InterruptedException e) %7B%0D%0A                handleShellException(e, command);%0D%0A            %7D%0D%0A
     
@@ -2242,18 +2242,16 @@
  catch (
-IO
 Exceptio
@@ -2266,182 +2266,8 @@
     
-        handleShellException(e, command);%0D%0A        %7D%0D%0A        return output.trim();%0D%0A    %7D%0D%0A%0D%0A    private static void handleShellException(Exception e, String... command) %7B%0D%0A
     
@@ -2303,32 +2303,36 @@
  %7B%0D%0A            
+    
 log.debug(%0D%0A    
@@ -2327,16 +2327,20 @@
 debug(%0D%0A
+    
         
@@ -2415,16 +2415,20 @@
 : %7B%7D%22,%0D%0A
+    
         
@@ -2481,25 +2481,71 @@
 );%0D%0A        
-%7D
+    %7D%0D%0A        %7D%0D%0A        return output.trim();
 %0D%0A    %7D%0D%0A%0D%0A 

Simplify exception handling when running a command in the shell