package com.sun.solarisinstall.panels;

//
// Copyright (c) 1996 Sun Microsystems, Inc., all rights reserved.
//

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.lang.*;
import java.net.*;

// 
// MyRun Class
//
public class MyRun {
	private boolean 	OutputFlag = false;
	private boolean 	InputFlag = false;
	private DataInputStream InputStream = null;
	private Process 	P = null;
	private int 		Result = -1;
	private String 		Output = null;
	private boolean		State = false;
	private String 		ErrorMsg = null;		
	
	//
	// Constructor #1
	// Simply run command
	// Input Arguments:
	//	String cmd: command line
	// 	boolean outputflag: output flag
	//
	// Output is going to stdout
	//

	public MyRun(String cmd, boolean outputflag) {
		OutputFlag = outputflag;
		runCommand(cmd);
	}

	private void runCommand(String cmd) {
		BufferedReader in = null;

		try {
			P = Runtime.getRuntime().exec(cmd);
			if ( P != null ) {
                                in = new BufferedReader(
                                  new InputStreamReader(
                                    new BufferedInputStream(
                                      P.getInputStream())));
				// Read its output
				if ( OutputFlag ) {
					myRead(in);
				}
				in.close();
				Result = P.waitFor();
				// Command runs OK
				State = true;
			}
			dispose(P);
		} catch (IOException ex) {
			if ( P == null ) {
			  	dispose(P);
				// Did not start the command
				ErrorMsg = "RunTime command: " + cmd + " failed";
			}
			System.out.println("MYRun Error:" + ex);
			
		} catch (InterruptedException ex) {
		  	dispose(P);
			if ( P == null ) {
				// Did not start the command
				ErrorMsg = "RunTime command: " + cmd + " failed";
			}
			System.out.println("MyRun Error:" + ex);
		}
	}

	public String getErrorMsg() { return ErrorMsg; }

	public boolean getState() { return State; }
	
	public int getResult() {
		if (P == null) {
			return (-1);
		}
		return P.exitValue();
	}

	public String getOutput() { return Output; }

	public void myRead(BufferedReader in) {
		String str = null;
		try {
			while ((str = in.readLine()) != null) {
				Output = str;
				//System.out.println(str);
			}
		} catch (IOException ex) {
			if ( ex instanceof EOFException ) {
				return;
			}
			System.out.println("MyRun Error:" + ex);
		}
		return;
	}
	private void dispose( Process p)
    	  {
	    try {
	      p.getInputStream().close();
	      p.getOutputStream().close();
	      p.getErrorStream().close();
	      p.destroy();
	    } catch (IOException ex) {
	      p.destroy();
	    }
	  }
}
