/* cups-pdf.c -- CUPS Backend 
   08.02.2003, Volker C. Behr
   Exp. Physik V, Uni Wuerzburg 

   This code may be freely distributed as long as this header 
   is preserved.						
  
   HISTORY:  
   02/14/2003 : 0.2    - script re-located to /usr/lib/cups/filter/cups-pdfgen
   02/12/2003 : 0.1    - first beta release			                */


#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stddef.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
  int c,fd1,fd2;
  char buffer[8192],*dogs[4];
  FILE *fp;

  dogs[0]=calloc(128,1);
  dogs[1]=calloc(128,1);
  dogs[2]=calloc(128,1);
  dogs[3]=NULL;
  if (argc==1) {
    printf("file cups-pdf:/ \"PDF Printer\" \"Virtual Printer\"\n");
    return 0;
  }
  if (argc<6 || argc>7) {
    fputs("Usage: cups-pdf job-id user title copies options [file]\n", stderr);
    return 1;
  }
  sprintf(dogs[1],"/var/spool/cups/tmp/cups2pdf-%i\0",(int) getpid());
  if (argc==6) {
    fp=fopen(dogs[1], "w+");
    while((c=fgetc(stdin))!=EOF)
      fputc(c,fp);
    fclose(fp);
  }
  else {
    fd1=open(argv[6], O_RDONLY);
    fd2=open(dogs[1], O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
    while(c=(int)read(fd1,buffer,8192))
      write(fd2,buffer,c);
    close(fd2);
    close(fd1);
  }
  sprintf(dogs[0],"/usr/lib/cups/filter/cups-pdfgen");
  sprintf(dogs[2],"%s",argv[2]);
  execvp(dogs[0],dogs);
  return 0;
} 
