/*
 * 5799-WZQ (C) COPYRIGHT IBM CORPORATION 1988
 * LICENSED MATERIALS - PROPERTY OF IBM
 * REFER TO COPYRIGHT INSTRUCTIONS FORM NUMBER G120-2083
 */
/* $Header:pps.c 12.1$ */
/* $ACIS:pps.c 12.1$ */
/* $Source: /ibm/acis/usr/src/ibm/lpfilter/pp4216/RCS/pps.c,v $ */

#ifndef lint
static char *rcsid = "$Header:pps.c 12.1$";
#endif



#include <stdio.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/psioctl.h>

#define MAXPS 4
 

char *psdevname[] = { "/dev/ps0",
                      "/dev/ps1",
                      "/dev/ps2",
                      "/dev/ps3" };

static int DEBUG = 0;
static char psbuf[1028];


main(argc,argv)
    int argc;
    char **argv;
    
{ int f, i, isps, psbuflen, stat;
  char *outfilename, *ttyname();
  char buf[1040];
  int psdev = -1;

    
   f = 1;
   outfilename = ttyname(f);
   isps = 0;
   if (outfilename) {
       for (i = 0; i < MAXPS; i++) {
           isps |=  !strcmp(outfilename, psdevname[i]);
       }
   }
   if (isps) {
       psdev = open(outfilename, O_RDONLY);
       if (psdev < 0) 
          syslog(LOG_ALERT|LOG_LPR, "cannot open %s for read\n", outfilename);
   }
  
   stat = 0;
   psbuflen = read(0, psbuf, 32);
   if (psbuflen < 0) {
       syslog(LOG_ALERT|LOG_LPR, "read failed\n");
       exit(2);
   }
   while (psbuflen > 0 && stat >= 0) {
       if (DEBUG) {
           syslog(LOG_DEBUG|LOG_LPR, "write %s\n", outfilename);
       }
       stat = write(f, psbuf, psbuflen);
       if (stat < 0) {
           syslog(LOG_ALERT|LOG_LPR, "write failed\n");
           exit(2);
       }
       psbuflen = read(0, psbuf, 32);
       if (psbuflen < 0) {
           syslog(LOG_ALERT|LOG_LPR, "read failed\n");
           exit(2);
       }
   }
      
   sleep(3); /* get a chance to pick up any output from the printer */

   if (isps & (psdev >= 0)) {
       stat = ioctl(psdev, PSREADPACKET, 0); 
       if (stat < 0) {
           syslog(LOG_ALERT|LOG_LPR, "pps: ioctl failed. f = %d, stat = %x\n", 
                   psdev, stat);
           exit(0); /* Don't return with an error because this does not */
       }            /* warrant reprinting the job                       */
      while (read(psdev, buf, 1028) > 0) {
          if (((short *)buf)[1] == 0x0080) {
              syslog(LOG_ALERT|LOG_LPR, "FROM %s:  %s\n", outfilename, buf+4);
          }
      }
   }
   exit(0);   
}



