/*
 *  dequeue_simple.c
 *
 *    A simple, single-threaded channel program to dequeue queued messages.
 *
 *  Copyright (c) 2003, Sun Microsystems, Inc.  All Rights Reserved.
 */

#include <stdio.h>
#include <stdlib.h>
#include "mtasdk.h"

static mta_dq_process_message_t process_message;

main()
{
     int ires;

     /*
      *  Initialize the MTA SDK
      */
     if ((ires = mtaInit(0)))
     {
	  mtaLog("mtaInit() returned %d; %s\n", ires, mtaStrError(ires, 0));
	  return(1);
     }

     /*
      *  Start the dequeue loop.  Since this example uses stdout for
      *  output, we indicate that we only support a single thread
      *  (MTA_THREAD_MAX_THREADS = 1).
      */
     ires = mtaDequeueStart(NULL, process_message, NULL,
			    MTA_THREAD_MAX_THREADS, 1, 0);

     /*
      *  Check the return status
      */
     if (!ires)
	  /*
	   *  Success
	   */
	  return(0);

     /*
      *  Print an error message and exit with an error
      */
     mtaLog("mtaDequeueStart() returned %d; %s\n", ires, mtaStrError(ires, 0));
     return(1);
}


/*
 *  process_message -- This routine is called for each message to be processed.
 */
static int process_message(void **my_ctx_2, void *my_ctx, mta_dq_t *dq,
			   const char *env_from, size_t env_from_len)
{
     int ires;
     size_t len;
     const char *to, *line;

     if (!(*my_ctx_2))
     {
	  *my_ctx_2 = (void *)1;
	  printf("HELO\n");
     }
     else
	  printf("RSET\n");

     /*
      *  Output the command
      *     MAIL FROM: <from-adr>
      */
     printf("MAIL FROM:<%s>\n", env_from);

     /*
      *  For each recipient address, output the command
      *     RCPT TO: <to-adr>
      */
     while (!(ires = mtaDequeueRecipientNext(dq, &to, &len, 0)))
     {
	  printf("RCPT TO:<%s>\n", to);
	  mtaDequeueRecipientDisposition(dq, to, len,
                                         MTA_DISP_DELIVERED, 0);
     }

     /*
      *  If ires == MTA_EOF, then we exited the loop normally;
      *  otherwise, there's been an error of some sort.
      */
     if (ires != MTA_EOF)
	  /*
	   *  An error -- defer processing of this message
	   */
	  return(ires);

     /*
      *  Now output the message itself
      */
     printf("DATA\n");
     while (!(ires = mtaDequeueLineNext(dq, &line, &len)))
	  printf("%.*s\n", len, line);

     /*
      *  If ires == MTA_EOF, then we exited the loop normally;
      *  otherwise, there's been an error of some sort.
      */
     if (ires != MTA_EOF)
	  /*
	   *  An error -- defer processing of this message
	   */
	  return(ires);

     /*
      *  Output the "." command to terminate this message
      */
     printf(".\n");

     /*
      *  And dequeue the message
      */
     ires = mtaDequeueMessageFinish(dq, 0);

     /*
      *  All done; might as well return ires as our result
      */
     return(ires);
}
