/* Find.c */

#include "Sys.h"

#include "Util.h"
#include "RCmd.h"
#include "Xfer.h"
#include "Cmds.h"
#include "Get.h"
#include "Find.h"

extern longstring gPager;
extern int gTransferType;
extern int gStdout;
extern gWinInit;

/* This is supposed to implement the Funet FTP Daemon's "FIND" command.
 * Unfortunately it doesn't work for a couple of reasons.
 *
 * First, it wants to use the data connection, which is fine, but it doesn't
 * send us a 100-level preliminary reply like the other data transfer
 * FTP commands do.
 *
 * Second, since the remote server has to do additional processing, data
 * isn't written to the data connection right away.  This is a problem
 * because NcFTP will timeout upon inactivity.
 *
 * I did an experiment, which got around these two problems, but it still
 * doesn't work well at all.  The find command will be listed as a
 * hidden command for now.
 */

int AsciiFind(char *pattern, int outfile)
{
	int result;
	XferSpecPtr xp;

	/* We do all finds in ascii mode for now. */
	SETASCII;
	
	/* Setup the parameter block to give to RDataCmd. */
	xp = InitXferSpec();
	xp->netMode = kNetReading;
	xp->getBlock = AsciiGetRemoteProc;
	xp->putBlock = AsciiPutLocalProc;
	xp->outStream = outfile;

	/* Send the request and do the transfer.  It really is a transfer
	 * since we use the data port.
	 */
	result = RDataCmd(xp, "FIND %s", pattern);
	DoneWithXferSpec(xp);

	return (result);
}	/* AsciiFind */




/* Ask server to look for something. */
int FindCmd(int argc, char **argv)
{
	FILE *fp;
	int fd;
	int result;
	int usingPager;

	/* We will use the pager automatically if not in visual mode. */
	if ((!gWinInit) || (gPager[0] == '\0')) {
		fd = gStdout;
		usingPager = 0;
	} else {
		SaveScreen();
		fp = POpen(gPager, "w");
		if (fp == NULL) {
			RestoreScreen(0);
			Error(kDoPerror, "Could not run %s.\n", gPager);
			return (kCmdErr);
		}
		fd = fileno(fp);
		usingPager = 1;
	}

	result = AsciiFind(argv[1], fd);

	if (usingPager) {
		(void) PClose(fp);
		RestoreScreen(1);
	}
	return (result);
}	/* FindCmd */
