/* parp-inject
 *
 * Take an e-mail off STDIN and place it in a spool directory
 * specified by the first argument.  Uses flock() to avoid races
 * with the filter.  You can test the locking via flock_test.sh.
 *
 * I am a very bad C programmer, and god does it show.
 *
 */

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>

#define MAX_FILENAME 32
#define MAX_PATH     1024 + 32 + 1  /* this is almost certainly wrong */
#define BUFSIZE      16384

void usage(char *program) {
  fprintf(stderr, "Usage: %s SPOOLDIR\n", program);
  exit(1);
}

int main(int argc, char **argv) {
  char path[MAX_PATH], filename[MAX_FILENAME], buf[BUFSIZE];
  FILE *mail;
  int fd;

  if (argc != 2) {
    usage(argv[0]);
  }

  /*
    Don't mkdir(); more likely to catch misspellings that way.
    mkdir(argv[1], 0700);
  */
  snprintf(filename, MAX_FILENAME, "%d.%d", time(NULL), getpid());
  snprintf(path, MAX_PATH, "%s/%s", argv[1], filename);

  umask(077);
  if (! (mail = fopen(path, "w"))) {
    fprintf(stderr, "parp-inject: Couldn't open %s for writing: ", path);
    perror("");
    return(1);
  }

  fd = fileno(mail);
  if (flock(fd, LOCK_EX | LOCK_NB) == -1) {
    fprintf(stderr, "Couldn't get exclusive lock on %s via flock(2): ", path);
    perror("");
    return(1);
  }

  while (! feof(stdin)) {
    fread(buf, BUFSIZE, 1, stdin);
    fprintf(mail, "%s", buf);
  }
  
  fclose(mail);

  return(0);
}

