#include <JInPipeStream.h>
#include <JOutPipeStream.h>
#include <jProcessUtil.h>
#include <JString.h>
#include <jStreamUtil.h>
#include <jDirUtil.h>
#include <jFileUtil.h>
#include <jUNIXUtil.h>
#include <signal.h>
#include <fstream.h>

const JCharacter* kFileName = "\"more junk\"";

int
main()
{
	cout << "Hello " << JGetUserName() << endl << endl;

	// test directory functions

	JString dir;
	if (JGetHomeDirectory(&dir))
		{
		cout << "home dir   : " << dir << endl;
		}

	dir = JGetCurrentDirectory();
	cout << "current dir: " << dir << endl;

	// test input pipe

	JString cmd = "ls -l " + JPrepArgForExec(dir);

	cout << endl;
	cout << "Here is what is in your current directory:" << endl;
	cout << endl;

	int fromFD;
	JError err = JExecute(cmd, NULL,
						  kJIgnoreConnection, NULL,
						  kJCreatePipe, &fromFD);
	if (err.OK())
		{
		JInPipeStream input(fromFD, kTrue);
		while (input.good())
			{
			const JString line = JReadLine(input);
			cout << line << endl;
			}
		}
	else
		{
		cerr << err.GetMessage() << endl;
		}

	// test output pipe

	cout << "Grepping for 'junk' in stuff that I print:" << endl;
	cout << endl;

	pid_t childPID;
	int toFD;
	err = JExecute("grep junk", &childPID, kJCreatePipe, &toFD);
	if (err.OK())
		{
		{
		JOutPipeStream output(toFD, kTrue);
		output << "This is line 1" << endl;
		output << "This is line 2" << endl;
		output << "This line contains 'junk'" << endl;
		}

		err = JWaitForChild(childPID);
		if (!err.OK())
			{
			cerr << err.GetMessage() << endl;
			}
		}
	else
		{
		cerr << err.GetMessage() << endl;
		}

	// test JPrepArgForExec with screwy file name

	ofstream output(kFileName);
	output << "This is line 1" << endl;
	output << "This is line 2" << endl;
	output.close();

	cout << endl;
	cout << "Contents of " << kFileName << ':' << endl;
	cout << endl;

	cmd = "cat " + JPrepArgForExec(kFileName);
	err = JExecute(cmd, NULL);
	if (!err.OK())
		{
		cerr << err.GetMessage() << endl;
		}

	err = JRemoveFile(kFileName);
	if (!err.OK())
		{
		cerr << err.GetMessage() << endl;
		}

	return 0;
}
