package org.forkalsrud.album.video;

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

import org.apache.commons.io.IOUtils;

public class ExecUtil {

    /**
     * The crazy Mac OSX does not even set the PATH to a reasonable value, so
     * we have to jump through hoops to guess where we may find the executables
     * for mplayer and friends.
     *
     * @param name
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public String findExecutableInShellPath(String name) throws IOException, InterruptedException {

        String executableForName = name;
        ProcessBuilder pb = new ProcessBuilder(Arrays.asList(System.getenv("SHELL")));
        pb.redirectErrorStream(true); // send errors to stdout
        Process p = pb.start();
        PrintStream stdin = new PrintStream(p.getOutputStream());
        stdin.print("echo $PATH");  // This is still not entirely portable. Windows would like %PATH%
        stdin.close();
        InputStream stdout = p.getInputStream();
        String searchPath = IOUtils.toString(stdout);
        p.waitFor();

        String separator = System.getProperty("path.separator");
        if (searchPath != null && separator != null && !"".equals(separator)) {
            String[] elements = searchPath.split(separator);
            for (String path : elements) {

                File executable = new File(path, name);
                if (executable.isFile()) {
                    executableForName = executable.getAbsolutePath();
                    break;
                }
            }
        }
        return executableForName;
    }

}
