/* Projet References -- Effacement des entrees expirees de la base par
 *                      recopie.
 * Auteur: Marc SCHAEFER <schaefer@alphanet.ch>
 * Date creation:     14/06/97
 * Date modification: 14/06/97
 * V1.0 PV001 MSC97
 * DESCRIPTION
 *    Ce programme copie les entrées non expirées de la base de
 *    référence dans un nouveau fichier, qui peut ensuite remplacer
 *    l'ancien.
 * RESULT
 *    0 si ok
 *    1 si error
 *    2 si pas de dbm
 * NOTES
 *    - Théoriquement plus efficace que le standard cleanup_ref().
 * BUGS
 *    - Partly tested.
 *    - Hard-coded constants; maybe should use lib.a
 *    - See ref.c
 * TODO
 *    - Rename the original file first.
 * BASED-ON
 *    cleanup_ref.c PV002 of 15/02/97.
 */

#include <stdio.h>
#include "config.h"
#include "ref_interface.h"

#define BOOL signed char
#define TRUE -1
#define FALSE 0

#define HISTORY_FILE "not_used"
#ifndef REF_DBM
#define REF_DBM "/var/spool/ifmail/refdb"
#endif
#ifndef NEW_REF_DBM
#define NEW_REF_DBM "/var/spool/ifmail/refdb_new"
#endif

#define MAX_ENTRY_LEN 1024
#define DAYSEC 86400
#define MAXDAYS 30 /* BUGS: should be configurable */

int main(void) {
   ref_private_t *ref_db = ref_init(REF_DBM);
   BOOL had_error = FALSE;

   if (ref_db) {
      ref_private_t *new_ref_db = ref_init(NEW_REF_DBM);

      if (new_ref_db) {
         char rfc_msgid[MAX_ENTRY_LEN];
         char ftn_msgid[MAX_ENTRY_LEN];
         time_t the_time;
         time_t nouveau = time(NULL);

         if (ref_first_key(ref_db, ftn_msgid, MAX_ENTRY_LEN)) {
	    do {
	       if (ref_get_extended(ref_db, ftn_msgid, rfc_msgid,
				    MAX_ENTRY_LEN, &the_time)) {
		  /* Verifie la date */
		  if (the_time<= nouveau) {
		     int days;

		     if ( (days = ((nouveau - the_time) / DAYSEC)) > MAXDAYS) {
#ifdef DEBUG
			printf("will not copy because %d days.\n", days);
#endif
		     }
		     else {
#ifdef DEBUG
			printf("will copy, days=%d.\n", days);
#endif
			if (!ref_store_extended(new_ref_db,
                                                ftn_msgid,
                                                rfc_msgid,
					        the_time)) {
			   had_error = TRUE;
			   fprintf(stderr, "error while storing\n");
			}
		     }
                  }
	       }
               else {
                  had_error = TRUE;
                  fprintf(stderr, "error while getting value\n");
               }
	    } while (!had_error && ref_next_key(ref_db, ftn_msgid,
			                        MAX_ENTRY_LEN));
	 }
         else {
	    had_error = TRUE;
	    fprintf(stderr, "no first key\n");
         }

         ref_deinit(new_ref_db);
         ref_deinit(ref_db);
      }
      else {
	 perror("could not open new_ref_db");
         ref_deinit(ref_db);
	 exit(2);
	 /* NOT REACHED */
      }
   }
   else {
     perror("could not open ref_db");
     exit(2);
     /* NOT REACHED */
   }

   exit(had_error ? 1 : 0);
}


