/*
**    spasm - The spasm anti-spam milter
**    Copyright (C) 2002 Sean Hanson <aradia@theasylum.org>
**
**    This program 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 of the License, or
**    (at your option) any later version.
**
**    This program 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 this program; if not, write to the Free Software
**    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <ctype.h>
#include <db2/db.h>

#include "spasm.h"

int main(int argc, char **argv)
{
    char data[256];
    char *val = NULL;
    DB *db;
    DB_ENV dbenv;
    DB_INFO dbinfo;
    DBT dbk, dbv;
    int dbfd;
    struct flock lfd;

    if(argc < 2) {
	printf("syntax: spasmdb <dbname> < inputfile.txt\n");
	exit(1);
    }

    if(chdir(BLACKLIST_DIR) != 0) {
        printf("Error changing directory: %m\n");
        exit(1);
    }

    memset(&dbenv, 0, sizeof(dbenv));
    memset(&dbinfo, 0, sizeof(dbinfo));
    dbinfo.db_pagesize = 512;
    unlink(argv[1]);
    if(db_open(argv[1], DB_HASH, DB_CREATE, 0644, &dbenv, &dbinfo, &db) != 0) {
	printf("Error opening database file: %m\n");
	exit(1);
    }
    if(db->fd(db, &dbfd) != 0) {
	printf("Error reading file descriptor for database: %m\n");
	exit(1);
    }
    memset(&lfd, 0, sizeof(lfd));
    lfd.l_type = F_WRLCK;
    if(fcntl(dbfd, F_SETLKW, &lfd) == -1) {
	printf("Error setting write lock on database: %m\n");
    }

    while(fgets(data, sizeof(data), stdin) != NULL) {
	if(strncmp(data, "#", 1) == 0) continue;
	val = data;
	while(isspace(*val) == 0) val++;
	*val = '\0';
	memset(&dbk, 0, sizeof(DBT));
	memset(&dbv, 0, sizeof(DBT));
	dbk.data = data;
	dbk.size = strlen(data);
	dbv.data = strdup("1");;
	dbv.size = strlen(dbv.data);
	db->put(db, NULL, &dbk, &dbv, 0);
    }

    if(db->sync(db, 0) != 0) {
        printf("Error syncing database: %m\n");
    }
    db->close(db, 0);
    exit(0);
}
