
/*
 *  SPRINT.C
 *
 *  DNET (c)Copyright 1988, Matthew Dillon, All Rights Reserved.
 *
 *  PRINTER SERVER
 *
 *  Accepting one connection at a time, dump the file to PRT:
 *
 *  DNET_WRITE	must be 6 or higher for this function to work.
 */

#include <stdio.h>
#include <fcntl.h>
#include "servers.h"

int Enable_Abort;

typedef struct Process PROC;

extern struct MsgPort *DListen();
extern PROC *FindTask();

extern void printfile();

_main()
{
    struct MsgPort *port;
    PROC    *myproc = FindTask(NULL);
    long    chan;
    long    savedir;
    long    mask, rmask;

    Enable_Abort = 0;

    if (myproc->pr_CLI) {
	Version("SPrint", VERSION, SPRINT_VERSION);
	_exit(0);
    }

    port = DListen(PORT_PRINTER);
    WaitPort(&myproc->pr_MsgPort);
    ReplyMsg(GetMsg(&myproc->pr_MsgPort));

    mask = SIGBREAKF_CTRL_C|(1 << port->mp_SigBit);
    for (;;) {
	rmask = Wait(mask);
	if (rmask & SIGBREAKF_CTRL_C)
	    break;
	while (chan = DAccept(port)) {
	    if (GetEnvVal(DNET_WRITE) >= 6) {
		DWrite(chan, "Accepted\n", 9);
		printfile(chan);
	    } else {
		DWrite(chan, "Permission Denied\n", 18);
	    }
	    DClose(chan);
	}
    }
    DUnListen(port);
}

void
printfile(chan)
{
    long n, fh;
    char rc = 0;
    char buf[256];

    if (fh = Open("PRT:", 1006)) {
	rc = 1;
	while ((n = DRead(chan, buf, 256)) > 0) {
	    if (Write(fh, buf, n) != n) {
		rc = 0;
		break;
	    }
	}
	Close(fh);
    }
    DWrite(chan, &rc, 1);
}

