
/*
 *  UUXQT.C by William Loftus
 *  Copyright 1988 by William Loftus.	All rights reserved.
 *  Changes Copyright 1990 by Matthew Dillon, All Rights Reserved
 *
 *  $Header: Beta:src/uucp/src/uucico/RCS/uuxqt.c,v 1.1 90/02/02 11:55:58 dillon Exp Locker: dillon $
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <log.h>
#include "version.h"
#include "protos.h"

IDENT(".06");

static char names[MAXFILES*16];
static char *pointers[MAXFILES];
static int file_pointer;
static int error;
static char *xfile;
static char dfile[128];
static char cmd[2048+1024];
static char ccmd[256];
static char ccmd_args[2048];
static char buf[2048];
static char path[256];

#define DELIM " \t\n\r"

int
brk()
{
    return(0);
}

int
bp_strcmp(s1, s2)
char **s1;
char **s2;
{
    return(strcmp(*s1, *s2));
}

int
work_scan()
{
    static char name[128];
    int count;

    file_pointer = 0;

    strcpy(name, MakeConfigPath(UUSPOOL, "X.#?"));

    count = getfnl(name,names,sizeof(names),0);

    if (count > 0) {
	printf("New files have arrived.\n");

	if (strbpl(pointers,MAXFILES,names) != count) {
	    printf("Too many execute files\n");
	    return(0);
	}
    } else {
	return(0);
    }
    qsort(pointers, count, sizeof(char *), bp_strcmp);
    return(1);
}

char *
work_next()
{
    char *ptr;

    if (ptr = pointers[file_pointer])
	++file_pointer;
    return(ptr);
}

parse(x)
char *x;
{
    FILE *fp;
    char *tmp;

    fp = fopen(x, "r");
    if (fp == (char *)NULL) {
	printf("Can't open file %s\n",x);
	chdir(path);
	return(0);
    }
    while (fgets(buf, sizeof(buf), fp)) {
	if (strncmp(buf, "F", 1) == 0)
	    strcpy(dfile, strtok(&buf[1],DELIM));
	else if (strncmp(buf, "C", 1) == 0) {       /*  Sept 90 */
	    strcpy(ccmd, strtok(&buf[1],DELIM));
	    strcpy(ccmd_args, strtok(NULL, DELIM));
	    while ((tmp = (char *)strtok(NULL, DELIM)) != NULL) {
		strcat(ccmd_args, " ");
		strcat(ccmd_args, tmp);
	    }
	}
    }

    if (strncmp(ccmd, "rmail", 5) == 0) {
	sprintf(cmd,"%s < %s %s", GetConfigProgram(RMAIL), dfile, ccmd_args);
    } else if (strncmp(ccmd, "cunbatch", 5) == 0) {
	sprintf(cmd,"%s < %s %s", GetConfigProgram(CUNBATCH), dfile, ccmd_args);
    } else if (strncmp(ccmd, "rnews", 5) == 0) {
	sprintf(cmd,"%s < %s", GetConfigProgram(RNEWS), dfile);
    } else {
	printf("Unknown command request %s  - Operation Aborted -\n", ccmd);
	error = 1;
    }
    fclose(fp);
    return(1);
}

main()
{
    long numFiles = 0;
    onbreak(brk);

    LogProgram = "UUXQT";

    getcwd(path,sizeof(path));
    chdir(GetConfigDir(UUSPOOL));

    LockFile("UUXQT");
    while (work_scan()) {
	while ((xfile = work_next()) != NULL) {
	    ++numFiles;
	    LockFile(xfile);
	    if (parse(xfile)) {
		int syserr;

		syserr = system(cmd);
		if (syserr == 0 && error != 1) {
		    remove(xfile);
		    remove(dfile);
		}
	    }
	    UnLockFile(xfile);
	}
    }
    UnLockFile("UUXQT");
    chdir(path);
    ulog(-1, "Processed %d files", numFiles);
    return(0);
}

