/*****************************************************************************
 *
 * File ..................: dbase/dbdupe.c
 * Purpose ...............: Dupe checking.
 * Last modification date : 19-Mar-1999
 *
 *****************************************************************************
 * Copyright (C) 1997-1999
 *   
 * Michiel Broek		FIDO:		2:2801/16
 * Beekmansbos 10		Internet:	mbroek@ux123.pttnwb.nl
 * 1971 BV IJmuiden
 * the Netherlands
 *
 * This file is part of MBSE BBS.
 *
 * This BBS is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * MBSE BBS is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MBSE BBS; see the file COPYING.  If not, write to the Free
 * Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 *****************************************************************************/


#include "../include/libs.h"
#include "../include/structs.h"
#include "../include/records.h"
#include "../common/common.h"
#include "dbdupe.h"



int CheckDupe(unsigned long crc, char *data, int max)
{
	char		dfile[81], tfile[81];
	FILE		*fil, *tmp;
	unsigned long	test;
	int		i = 0;

	sprintf(dfile, "%s/etc/%s.dupe", getenv("MBSE_ROOT"), data);
	if ((fil = fopen(dfile, "r+")) == NULL) {
		/*
		 * Dupe database doesn't exist yet.
		 */
		if ((fil = fopen(dfile, "w")) == NULL) {
			perror("");
			printf("PANIC: dbdupe.c, can't create %s", dfile);
			exit(1);
		}
		/*
		 * Write first dupe in database, return false of course
		 */
		fwrite(&crc, sizeof(crc), 1, fil);
		fclose(fil);
		return FALSE;
	}

	/*
	 * Dupe file exists, check if we have a dupe.
	 */
	while (fread(&test, sizeof(test), 1, fil) == 1) {
		if (test == crc) {
			/*
			 * We have found a duplicate
			 */
			fclose(fil);
			return TRUE;
		}
	}

	/*
	 * Not a dupe, append new crc value
	 */
	fwrite(&crc, sizeof(crc), 1, fil);
	test = ftell(fil);
	fclose(fil);

	/*
	 * Here we should check the size of the file. If we are
	 * above the "max" size, we truncate the file 10%.
	 */
	if (max && (test > (max * sizeof(unsigned long)))) {
		Syslog('+', "Removing dupes from %s", dfile);
		sprintf(tfile, "%s/etc/%s.temp", getenv("MBSE_ROOT"), data);
		fil = fopen(dfile, "r");
		tmp = fopen(tfile, "w");
		fseek(fil, (- (max - (max / 10))) * sizeof(unsigned long), SEEK_END);
		while (fread(&test, sizeof(unsigned long), 1, fil) == 1) {
			fwrite(&test, sizeof(unsigned long), 1, tmp);
			i++;
		}
		Syslog('+', "Written %d dupe records", i);
		fclose(fil);
		fclose(tmp);
		unlink(dfile);
		rename(tfile, dfile);
	}

	return FALSE;
}



