/* RunCommand.java */

import java.io.*;

public class RunCommand
{
  static final int MODE_UNCONNECTED = 0;
  static final int MODE_WAITFOR     = 1;
  static final int MODE_CATCHOUTPUT = 2;

  private static void runCommand(String cmd, int mode)
  throws IOException
  {
    Runtime rt = Runtime.getRuntime();
    System.out.println("Running " + cmd);
    Process pr = rt.exec(cmd);
    if (mode == MODE_WAITFOR) {
      System.out.println("waiting for termination");
      try {
        pr.waitFor();
      } catch (InterruptedException e) {
      }
    } else if (mode == MODE_CATCHOUTPUT) {
      System.out.println("catching output");
      BufferedReader procout = new BufferedReader(
        new InputStreamReader(pr.getInputStream())
      );
      String line;
      while ((line = procout.readLine()) != null) {
        System.out.println("  OUT> " + line);
      }
    }
    try {
      System.out.println(
        "done, return value is " + pr.exitValue()
      );
    } catch (IllegalThreadStateException e) {
      System.out.println(
        "ok, process is running asynchronously"
      );
    }
  }

  private static void runShellCommand(String cmd, int mode) 
  throws IOException
  {
    String prefix = "";
    String osName = System.getProperty("os.name");
    osName = osName.toLowerCase();
    if (osName.indexOf("windows") != -1) {
      if (osName.indexOf("95") != -1) {
        prefix = "command.com /c ";
      } else if (osName.indexOf("98") != -1) {
        prefix = "command.com /c ";
      }
    }
    if (prefix.length() <= 0) {
      System.out.println(
        "unknown OS: don\'t know how to invoke shell"
      );
    } else {
      runCommand(prefix + cmd, mode);
    }
  }

  public static void main(String[] args)
  {
    try {
      if (args.length <= 0) {
        System.out.println(
          "Usage: java RunCommand [-shell] " +
          "[-waitfor|-catchoutput] <command>"
        );
        System.exit(1);
      }
      boolean shell = false;
      int mode = MODE_UNCONNECTED;
      String cmd = "";
      for (int i = 0; i < args.length; ++i) {
        if (args[i].startsWith("-")) {
          if (args[i].equals("-shell")) {
            shell = true;
          } else if (args[i].equals("-waitfor")) {
            mode = MODE_WAITFOR;
          } else if (args[i].equals("-catchoutput")) {
            mode = MODE_CATCHOUTPUT;
          }
        } else {
          cmd = args[i];
        }
      }
      if (shell) {
        runShellCommand(cmd, mode);
      } else {
        runCommand(cmd, mode);
      }
    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
}