
/*
 *  UUXQT.C by William Loftus
 *  Copyright 1988 by William Loftus.	All rights reserved.
 *
 *  Beta Version 0.31
 *
 */

#include <stdio.h>
#include <string.h>
#include "/version.h"

IDENT(".01");

static char names[3000];
static char *pointers[300];
static int file_pointer;
static int error;
static char* xfile;
static char dfile[128];
static char cmd[1024];
static char ccmd[128];
static char ccmd_args[128];
static char buf[128];
static char path[128];

#define DELIM " \t\n\r"

CXBRK()
{
    return(0);
}

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

    file_pointer = 0;

    sprintf(name,"UUSPOOL:X.#?");

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

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

	if (strbpl(pointers,300,names) != count) {
	    printf("Too many execute files\n");
	    return (char *)NULL;
	}
    } else {
	return (char *)NULL;
    }
    return (char *)1;
}

char *
work_next()
{
    return pointers[file_pointer++];
}

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)
	    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,"uucp:c/rmail < %s %s", dfile, ccmd_args);
    } else if (strncmp(ccmd, "cunbatch", 5) == 0) {
	sprintf(cmd,"uucp:c/cunbatch < %s %s", dfile, ccmd_args);
    } else if (strncmp(ccmd, "rnews", 5) == 0) {
	sprintf(cmd,"uucp:c/rnews < %s %s", dfile, "UseNet");
    } else {
	printf("Unknown command request %s  - Operation Aborted -\n", ccmd);
	error = 1;
    }
    fclose(fp);
    return(1);
}


void
main()
{
    getcwd(path,128);
    chdir("UUSPOOL:");
    if (work_scan() != (char *)NULL) {
	while ((xfile = work_next()) != (char *)NULL) {
	    LockFile(xfile);
	    if (parse(xfile)) {
		int syserr;
		if (syserr = system(cmd + 7))
		    syserr = system(cmd);
		if (syserr == 0 && error != 1) {
		    remove(xfile);
		    remove(dfile);
		}
	    }
	    UnLockFile(xfile);
	}
    }
    chdir(path);
}

