/* $Id: split_std_mailbox.cc 3468 2009-06-30 12:26:42Z flaterco $ */
// g++ -Wall -Wextra -pedantic -O2 -s -o split_std_mailbox split_std_mailbox.cc -ldstr

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <Dstr>


FILE *newmsg (char *dest_dir) {
  static const unsigned bufsize = 1000;
  static unsigned long serialnum = 0;
  size_t l;
  char msgfilename[bufsize];
  FILE *fp;
  struct stat stat_struct;

  l = strlen(dest_dir);
  assert (l > 0);
  assert (l + 80 < bufsize);
  strcpy (msgfilename, dest_dir);
  if (msgfilename[l-1] != '/')
    msgfilename[l++] = '/';
  do
    sprintf (msgfilename+l, "msg%lu", serialnum++);
  while (stat (msgfilename, &stat_struct) == 0);
  if (!(fp = fopen (msgfilename, "w"))) {
    perror (msgfilename);
    fprintf (stderr, "Aborting run\n");
    exit (-1);
  }
  return fp;
}


int main (int argc, char **argv) {
  FILE *mbox, *msg=NULL;
  Dstr inbuf;
  bool prevLineBlank (true);

  if (argc != 3) {
    fprintf (stderr, "Usage:  split_std_mailbox mailbox-filename destination-directory\n");
    exit (-1);
  }
  if (!(mbox = fopen (argv[1], "r"))) {
    perror (argv[1]);
    exit (-1);
  }

  while (!inbuf.getline(mbox).isNull()) {
    // Had trouble with unquoted Froms in messages.  The address
    // condition would be too restrictive on systems where local mail
    // gets use.  Exchange server uses 'unknown'.
    if (prevLineBlank &&
        (inbuf.strchr('@') != -1
         || inbuf.strstr("MAILER-DAEMON") != -1
         || !(strncmp (inbuf.aschar(), "From unknown", 12))
         || !(strncmp (inbuf.aschar(), "From <>", 7))) &&
        !(strncmp (inbuf.aschar(), "From ", 5))) {
      if (msg)
        fclose (msg);
      msg = newmsg (argv[2]);
    }
    if (!msg) {
      fprintf (stderr, "Beginning From line not found.\n");
      exit (-1);
    }
    fprintf (msg, "%s\n", inbuf.aschar());
    prevLineBlank = (inbuf.length() == 0);
  }

  fclose (mbox);
  if (msg)
    fclose (msg);
  return 0;
}
