/*
 * trust.c
 * (C) Christian Magnusson 1999, Email: d1mag@dtek.chalmers.se
 * This program is copyright, and covered by the Gnu Public License.
 * The Q bot.
 */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#include "settings.h"
#include "bottypes.h"
#include "globals.h"


struct trusted *trusted_add(char *host, int nr, time_t expire, char *reason, int placedby)
{
	struct trusted *tr, *tr2;
	ListElem *el;
	int already_exist = 0;
	int rlen;

	if (!host)
		return 0;
	if (!reason)
		return 0;

	tr = (struct trusted *) Malloc(sizeof(struct trusted));
	if (!tr)
		return 0;
	memset(tr, 0, sizeof(struct trusted));
	rlen = MIN(strlen(reason), REASONLEN);
	tr->reason = (char *) Malloc(rlen + 1);
	if (!tr->reason) {
		Free(tr);
		return 0;
	}
	strncpy(tr->reason, reason, rlen);
	tr->reason[rlen] = '\0';

	rlen = MIN(strlen(host), REASONLEN);
	tr->host = (char *) Malloc(rlen + 1);
	if (!tr->host) {
		Free(tr->reason);
		Free(tr);
		return 0;
	}
	strncpy(tr->host, host, rlen);
	tr->host[rlen] = '\0';

	tr->placedby = placedby;
	tr->expire = expire;
	tr->nr_users = nr;

	el = GetHead(trusted_list);
	already_exist = 0;
	while (el) {
		tr2 = (struct trusted *) (el->data);
		if (!strcasecmp(tr2->host, tr->host)) {
			already_exist = 1;
			break;
		}
		el = GetSucc(el);
	}
	if (already_exist) {
		Free(tr->host);
		Free(tr->reason);
		Free(tr);
		return 0;
	} else {
		el = NewElem(tr);
		AddTail(trusted_list, el);
	}
	return tr;
}

int trusted_del(char *host)
{
	struct trusted *tr = NULL;
	ListElem *el;

	if (!host)
		return -1;

#if DEBUG
	log("trusted_del: [%s]\n", host);
#endif

	el = GetHead(trusted_list);
	while (el) {
		tr = (struct trusted *) (el->data);
		if (!strcasecmp(tr->host, host)) {
			break;
		}
		el = GetSucc(el);
	}
	if (!el) {
		/* not found */
		return 0;
	}

	Free(tr->host);
	tr->host = NULL;
	Free(tr->reason);
	tr->reason = NULL;
	Remove(el);
	FreeElem(el);
	return 1;
}
