/***************************************
  $Revision: 1.17 $

  Example code: MIME parser.

  Design and implementation by: Daniele Arena

  ******************/ /******************
  Modification History:
        daniele (20/07/2000) Created.
  ******************/ /******************
  Copyright (c) 2000                              RIPE NCC
 
  All Rights Reserved
  
  Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose and without fee is hereby granted,
  provided that the above copyright notice appear in all copies and that
  both that copyright notice and this permission notice appear in
  supporting documentation, and that the name of the author not be
  used in advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.
  
  THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
  AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  ***************************************/


/* Included headers: */

/* Standard headers */
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <sys/time.h>


/* This is the header to include the MM module*/
#include "mm.h"
#include "mail_parser.h"
#include "erroutines.h"


/* Other modules */
#include "ca_configFns.h"
#include "ca_dictSyms.h"
#include "ca_macros.h"


/* Global variables */

char *gpgcmd = NULL;


/* This is the temporary file where stdin is stored by MM_store */
/* #define MAIL_FILE "/tmp/daniele/mm.unprocessed" */
#define DEFLT_CONFIG_FILENAME "ripedb.config"

/* Function declaration */
int main (int argc, char* argv[]);
void usage(char *argv[]);


void error_init(int argc, char ** argv) 
{

  char *slash;     
  char progname[32];
  
  slash = rindex(argv[0],'/');                            
  strncpy(progname, (slash != NULL) ? slash+1 : argv[0], 31);
  progname[31]=0;
  

  ER_init(progname, 0);

  {
    char *err_msg = NULL;
    char *buf = 
      "CREATE testdbg { FORMAT PROGNAME|PIDFULL|SEVCHAR|FACSYMB|TEXTLONG|DATETIME NAME /tmp/mmtest.dbg DATE }"
      "( FAC mm ASP MM_GEN SEV d-f ) "
      ;
    char *buf2 =
      "CREATE testinf { FORMAT PROGNAME|PIDFULL|SEVCHAR|FACSYMB|TEXTLONG|DATETIME NAME /tmp/mmtest.inf DATE }"
      "( FAC mm ASP MM_GEN SEV i-f ) "
      ;
    
    int parsres = ER_parse_spec(buf, &err_msg);
    
    if( parsres != 0 ) 
      { 
	/* print only on failure */
	puts(err_msg);
      }
    
    free(err_msg);
    
    if( parsres == 0 ) 
      { 
	/* success */
	char *pbuf = NULL;
	
	er_print_paths(&pbuf);
	puts(pbuf);
	free(pbuf);
      }
    else 
      die;

    
    parsres = ER_parse_spec(buf2, &err_msg);
    
    if( parsres != 0 ) 
      { 
	/* print only on failure */
	puts(err_msg);
      }
    
    free(err_msg);
    
    if( parsres == 0 ) 
      { 
	/* success */
	char *pbuf = NULL;
	
	er_print_paths(&pbuf);
	puts(pbuf);
	free(pbuf);
      }
    else 
      die;
  }
  
}


/* Main program - initialization */

int main (int argc, char *argv[])
{
 
  long debug = 0;
  long mesgno;
  int retcode;
  /* MM_header *mail_header = NULL; */
  /* EP_Mail_Descr *mail_header; */
  EP_Mail_Descr *mail_elmt;
  Mail_Header_Field *mhfp;
  char mail_file[FILENAMELEN];
  char *input_file;
  extern char *optarg;
  extern int optind;
  int ch;
  short sflg = 0;
  short fflg = 0;
  short errflg = 0;
  char *config_filename = NULL;
  char *tmpdir = NULL;

  /* EP_mail_node *mailtree; */


  while ((ch = getopt(argc, argv, "sf:d:c:h")) != EOF)
    switch((char)ch) 
      {
      case 's':
	if (fflg)
	  errflg++;
	else
	  {
	    sflg++;
	    input_file = (char *)malloc(STR_S);
	    sprintf (input_file,"-");
	  }
	break;
      case 'f':
	if (sflg)
	  errflg++;
	else
	  {
	    fflg++;
	    input_file = optarg;
	  }
	break;
      case 'd':
	debug = atol (optarg);
	break;
      case 'c':
	config_filename = strdup(optarg);
	break;
      case 'h':
      default:
	errflg++;
      }

  if (errflg)
    usage(argv);


  /* N.B.: There should be only one message in the file,
   * so mesgno should always be 1.
   * If you want a general MIME parser, you should add an option
   * to read mesgno.
   */


  /* For memory leak tests */
  /*   
       for (;;)
       {
       printf ("Pass # %d\n",j++);
       for (k = 1; k < 10000000; k++)
       {} 
       */

  mesgno = 1;



  /* Config stuff */
  /*  ca_populateDictionary(dictionary, VARS);
   
   if(config_filename != NULL)
     ca_readConfig(config_filename, confVars, VARS);
   else
     ca_readConfig(DEFLT_CONFIG_FILENAME, confVars, VARS); */
   
  if(config_filename != NULL)
    ca_init(config_filename);
  else
    ca_init(DEFLT_CONFIG_FILENAME);
  

  /* Get variables from config file */
  tmpdir = ca_get_tmpdir;
  gpgcmd = ca_get_pgpv;

  /* Initialize error handling */
  error_init(argc, argv);



  /*sprintf (mail_file,"%s",MAIL_FILE); */     /* the file where the mail message will be stored */


  /* Put stdin in the mail file */

  /*if ((retcode = MM_store(input_file,mail_file, debug)) != 0)
    exit (retcode);
    */

  /* Allocate memory for the header */

  /* mail_header = (EP_Mail_Descr *)malloc(sizeof(EP_Mail_Descr)); */

  /* mail_elmt = InitializeMailDescr(mail_file); */

  
  /* if ((retcode = MM_get_msg_headers(mail_file, mail_elmt, mesgno, debug)) != 0) */
  /* if ((mail_elmt = InitializeMailDescr(mail_file)) == NULL) */
  if ((mail_elmt = EP_ParseMail(input_file, tmpdir, "/home/daniele/.gnupg/pubring.gpg", gpgcmd)) == NULL)
    {
      /* Temporary... */
      retcode = 1;
      
      printf ("Trouble in InitializeMailDescr()! Return code = %d\n",retcode);
      exit(retcode);
    }
  else
    {
      
      printf ("Mail headers:\n\n");
      
      printf ("From - %s",mail_elmt->from->field);
      
      printf ("Subject - %s",mail_elmt->subject->field);
      
      printf ("Date - %s",mail_elmt->date->field);
      
      printf ("Message-ID - %s",mail_elmt->message_id->field);
      
      printf ("Reply-To - ");
      for (mhfp = mail_elmt->reply_to; mhfp != NULL; mhfp = mhfp->next)
	printf ("%s",mhfp->field);  
      
      printf ("Cc - %s",mail_elmt->cc->field);

      printf ("Content-Type - %s",mail_elmt->content_type->field);

      /*  } */


  /* mailtree = EP_InitializeRootNode(mail_file); */

      /* if ((retcode = MM_extract_mime(mail_file, NULL, mail_elmt->tree, debug)) != 0)
    {
      exit (retcode);
    }
  else
    { */

      /* replace this with tree surfing */
      /* partptr = part_list->head;
      
      while (partptr != NULL)
	{
	  
	  printf("-----------------------------------------\n");
	  printf ("Section: %s\n",partptr->number);
	  printf ("Content-type: %s\n",partptr->type);
	  if (partptr->supported)
	    printf ("Supported\n");
	  else
	    printf ("Unsupported\n");
	  if (debug) printf ("=== DEBUG: Reading file %s...\n",partptr->file);
	  read_file(partptr->file);

	  printf ("\n\n");
	  partptr = partptr->next;
	} */
      

      /* Clean up the temporary files */
      /* MM_cleanup(part_list,debug); */

      EP_ShowTree(mail_elmt->tree);

      /* EP_MailDescrCleanUp(mail_elmt); */
    }

  /* Closing the memory leak test... */
  /* }  */

  exit (0);

  
} /* main */



void usage(char *argv[])
{
  printf ("Usage: \n");
  printf ("%s -s [-d debug] < input-message \n", argv[0]);
  printf ("%s -f input-message [-d debug] \n", argv[0]);
  printf ("    Default debug level: %d\n",DEFAULT_DEBUG);
  /* DEFAULT_DEBUG is defined in mm.h */
  exit (1);
}

