/*
 * gline.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"


int matches_gline(struct activeuser *u, struct gline *g)
{
	if (match(g->user, u->username)) {
		return 0;
	}
	if (match(g->host, u->hostname)) {
		return 0;
	}
	return 1;
}

struct gline *gline_add(char *gline, char *duration, char *reason, int placedby, int force_update)
{
	long durationl;
	time_t t;
	struct gline *g, *gp = NULL;
	ListElem *el;
	int already_exist = 0;
	int rlen;

	if (!gline)
		return 0;
	if (!duration)
		return 0;
	if (!reason)
		return 0;

	g = (struct gline *) Malloc(sizeof(struct gline));
	if (!g)
		return 0;
	rlen = MIN(strlen(reason), REASONLEN);
	g->reason = (char *) Malloc(rlen + 1);
	if (!g->reason) {
		Free(g);
		return 0;
	}
	strncpy(g->reason, reason, rlen);
	g->reason[rlen] = '\0';
	if (g->reason[rlen - 1] == '\012' || g->reason[rlen - 1] == '\015') {
		rlen--;
		g->reason[rlen] = '\0';
	}
	if (g->reason[rlen - 1] == '\012' || g->reason[rlen - 1] == '\015') {
		rlen--;
		g->reason[rlen] = '\0';
	}
#if DEBUG
	log("gline_add: [%s] [%s] [%s]\n", gline, duration, reason);
#endif
	strncpy(g->gline, gline, GLINELEN);
	g->gline[GLINELEN] = '\0';
	t = time(NULL);
	durationl = atol(duration);
	g->duration = durationl;
	t += durationl;
	g->expire = t;
	g->placedby = placedby;

	el = GetHead(gline_list);
	already_exist = 0;
	while (el) {
		gp = (struct gline *) (el->data);
		if (!strcasecmp(gp->gline, g->gline)) {
			already_exist = 1;
			break;
		}
		el = GetSucc(el);
	}
	if (already_exist && !force_update) {
		return 0;
	} else {
		if (already_exist && gp) {
			placedby = gp->placedby;
			Remove(el);
			Free(gp->reason);
			Free(gp);
			g->placedby = placedby;
		}
		el = NewElem(g);
		AddTail(gline_list, el);
	}
	return g;
}


int gline_del(char *gline)
{
	struct gline *gp = NULL;
	ListElem *el;

	if (!gline)
		return -1;

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

	el = GetHead(gline_list);
	while (el) {
		gp = (struct gline *) (el->data);
		if (!strcasecmp(gp->gline, gline)) {
			break;
		}
		el = GetSucc(el);
	}
	if (!el) {
		/* not found */
		return 0;
	}

	Free(gp->reason);
	Remove(el);
	FreeElem(el);
	return 1;
}
