/*---------------------------------------------------------------------------

 Copyright (c) 2005
	by Dirk Meyer, All rights reserved.
	Im Grund 4, 34317 Habichtswald, Germany
	Email: dirk.meyer@dinoex.sub.org

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
 3. Neither the name of the author nor the names of any co-contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.

-----------------------------------------------------------------------------

	avoice - a plugin for hexchat2
	============================

	$Id: avoice.c,v 1.13 2006/11/11 23:10:42 dm Exp $

----------------------------------------------------------------------------*/

#include "hexchat-plugin.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdarg.h>
#include <ctype.h>

#include <fcntl.h>
#ifdef linux
#include <sys/file.h>
#include <db_185.h>
#else
#include <db.h>
#endif


int hexchat_plugin_init(hexchat_plugin *plugin_handle,
	const char **plugin_name,
	const char **plugin_desc,
	const char **plugin_version,
	const char *arg);
void hexchat_plugin_deinit(void);


#define	MAX_BUF	1024


typedef struct _queue_entry {
	struct _queue_entry *q_next;
	char *q_data;
} queue_entry;


static hexchat_plugin *ph; /* plugin handle */
static hexchat_hook *timerhook = NULL;
static int enable = 1;
static char *configdir = NULL;
static char *voice_db = NULL;
static char *options_db = NULL;
static const char *watched_channel = "#anime-fansubs";
static time_t next_devoice = 0;
static queue_entry *notice_queue = NULL;
static char fbuf[MAX_BUF];
static char kbuf[MAX_BUF];
static char nbuf[MAX_BUF];
static char qbuf[MAX_BUF];


static void
string_to_lowercase(char *buffer)
{
	char *work;

	if (buffer == NULL)
		return;
	for (work = buffer; *work != 0; work ++) {
		if (isupper(*work))
			*work = tolower(*work);
	}
}

static queue_entry *
queue_init(const char *data)
{
	queue_entry *new;

	new = malloc(sizeof(queue_entry));
	if (new == NULL) {
		hexchat_printf(ph, "new queue, out of mem\n");
		return NULL;
	}
	new->q_next = NULL;
	new->q_data = (data != NULL) ? strdup(data) : NULL;
	return new;
}

static void
queue_add(queue_entry **queue, const char *data)
{
	queue_entry *old;
	queue_entry *new;

	if (queue == NULL)
		return;

	new = queue_init(data);
	if (*queue == NULL) {
		*queue = new;
		return;
	}
	old = *queue;
	while (old->q_next != NULL)
		old = old->q_next;
	old->q_next = new;
}

static char *
queue_get(queue_entry **queue)
{
	queue_entry *old;
	char *data;

	if (queue == NULL)
		return NULL;

	old = *queue;
	if (old == NULL)
		return NULL;

	*queue = old->q_next;
	data = old->q_data;
	free(old);
	return data;
}

static void
queue_delete(queue_entry **queue)
{
	queue_entry *old;

	if (queue == NULL)
		return;

	old = *queue;
	if (old == NULL)
		return;

	while (old != NULL) {
		if (old->q_data != NULL)
			free(old->q_data);
		*queue = old->q_next;
		free(old);
		old = *queue;
	}
	return;
}

static char *
queue_addf(queue_entry **queue, const char *format, ...)
#ifdef __GNUC__
__attribute__ ((format(printf,2,3)))
#endif
;

static char *
queue_addf(queue_entry **queue, const char *format, ...)
{
	va_list ap;

	va_start(ap, format);
	vsnprintf(qbuf, sizeof(qbuf), format, ap);
	va_end(ap);
	queue_add(queue, qbuf);
	return qbuf;
}


static char *
localdb_read(const char *name, const char *hash)
{
	DB *db;
	DBT key, data;
	char *hash2;
	char *str = NULL;
	int rc;

	db = dbopen(name, O_RDONLY, 0600, DB_HASH, NULL);
	if (db == NULL) {
		if (errno == ENOENT)
			return NULL;
		hexchat_printf(ph, "open database %s failed\n", name);
		return NULL;
	};

	/* generate entry */
	hash2 = strdup(hash);
	if (hash2 == NULL) {
		hexchat_printf(ph, "database %s, out of mem\n", name);
		db->close(db);
		return NULL;
	};
	key.data = hash2;
	key.size = strlen(key.data);
	data.data = NULL;
	data.size = 0;
	data.size = sizeof(fbuf) - 1;
	rc = db->get(db, &key, &data, 0);
	if (rc == 0) {
		if ((data.data != NULL) && (data.size > 0) && (data.size < sizeof(fbuf))) {
			strncpy(fbuf, data.data, data.size);
			fbuf[data.size] = 0;
			if (fbuf[data.size - 1] == '\n')
				fbuf[data.size - 1] = 0;
			str = fbuf;
		} else {
			hexchat_printf(ph, "database %s, get failed, size = %d\n", name, data.size);
		}
	} else {
		if (rc != 1)
			hexchat_printf(ph, "database %s, read returns %d\n", name, rc);
	}
	free(hash2);
	db->close(db);
	return str;
}

static void
localdb_delete(const char *name, const char *hash)
{
	DB *db;
	DBT key;
	char *hash2;
	int fd;
	int st;
	int rc;

	db = dbopen(name, O_RDWR|O_CREAT, 0600, DB_HASH, NULL);
	if (db == NULL) {
		hexchat_printf(ph, "open database %s failed\n", name);
		return;
	};

	/* lock all changes */
	fd = db->fd(db);
	if (fd == -1) {
		st = -1;
		hexchat_printf(ph, "database %s, bad fd\n", name);
	} else {
		st = flock(fd, LOCK_EX);
	}

	if (st == 0) {
		/* generate entry */
		hash2 = strdup(hash);
		if (hash2 == NULL) {
			hexchat_printf(ph, "database %s, out of mem\n", name);
			db->close(db);
			return;
		}
		key.data = hash2;
		key.size = strlen(key.data);
		rc = db->del(db, &key, 0);
		if ((rc != 0) && (rc != 1))
			hexchat_printf(ph, "database %s, delete returns %d\n", name, rc);
		db->sync(db,0);
		free(hash2);
		st = flock(fd, LOCK_UN);
	} else {
		hexchat_printf(ph, "database %s, lock failed\n", name);
	}
	db->close(db);
}

static void
localdb_write(const char *name, const char *hash, const char *value)
{
	DB *db;
	DBT key, data;
	char *hash2;
	int fd;
	int st;
	int rc;

	db = dbopen(name, O_RDWR|O_CREAT, 0600, DB_HASH, NULL);
	if (db == NULL) {
		hexchat_printf(ph, "open database %s failed\n", name);
		return;
	};

	/* lock all changes */
	fd = db->fd(db);
	if (fd == -1) {
		st = -1;
		hexchat_printf(ph, "database %s, bad fd\n", name);
	} else {
		st = flock(fd, LOCK_EX);
	}

	if (st == 0) {
		/* generate entry */
		hash2 = strdup(hash);
		if (hash2 == NULL) {
			hexchat_printf(ph, "database %s, out of mem\n", name);
			db->close(db);
			return;
		};
		key.data = hash2;
		key.size = strlen(key.data);
		snprintf(fbuf, sizeof(fbuf), "%s", value);
		data.data = fbuf;
		data.size = strlen(fbuf);
		rc = db->put(db, &key, &data, 0);
		if ((rc != 0) && (rc != 1))
			hexchat_printf(ph, "database %s, write returns %d\n", name, rc);
		db->sync(db,0);
		free(hash2);
		st = flock(fd, LOCK_UN);
	} else {
		hexchat_printf(ph, "database %s, lock failed\n", name);
	}
	db->close(db);
}

static long
localdb_info(const char *name)
{
	DB *db;
	DBT key, data;
	long entries;
	int ret;

	entries = 0;
	db = dbopen(name, O_RDWR, 0600, DB_HASH, NULL);
	if (db == NULL) {
		if (errno != ENOENT)
			hexchat_printf(ph, "open database %s failed\n", name);
		return entries;
	};

	/* cleanup old entrys */
	ret = db->seq(db, &key, &data, R_FIRST);
	while (!ret) {
		entries ++;
		ret = db->seq(db, &key, &data, R_NEXT);
	}
	db->close(db);
	return entries;
}

static void
localdb_list(const char *name)
{
	DB *db;
	DBT key, data;
	time_t now;
	time_t val;
	int ret;

	next_devoice = 0;
	db = dbopen(name, O_RDWR, 0600, DB_HASH, NULL);
	if (db == NULL) {
		if (errno != ENOENT)
			hexchat_printf(ph, "open database %s failed\n", name);
		hexchat_commandf(ph,
			"notice %s Keine Einträge in der Voice-Liste vorhanden.\n",
			nbuf);
		return;
	};

	/* cleanup old entrys */
	now = time(NULL);
	ret = db->seq(db, &key, &data, R_FIRST);
	while (!ret) {
		if ((key.data == NULL) || (key.size <= 0) || (key.size >= sizeof(kbuf))) {
			hexchat_printf(ph, "database %s, oversized key\n", name);
			break;
		};
		if ((data.data == NULL) || (data.size <= 0) || (data.size >= sizeof(fbuf))) {
			hexchat_printf(ph, "database %s, oversized key\n", name);
			break;
		};

		strncpy(kbuf, key.data, key.size);
		kbuf[key.size] = 0;
		if (kbuf[key.size - 1] == '\n')
			kbuf[key.size - 1] = 0;
		strncpy(fbuf, data.data, data.size);
		fbuf[data.size] = 0;
		if (fbuf[data.size - 1] == '\n')
			fbuf[data.size - 1] = 0;

		val = atol(fbuf);
		if (val <= now) {
			queue_addf(&notice_queue,
				"notice %s \"%s\" hatte Voice bis: %s (expired)",
				nbuf, kbuf, ctime(&val));
		} else {
			queue_addf(&notice_queue,
				"notice %s \"%s\" hat Voice bis: %s",
				nbuf, kbuf, ctime(&val));
		}

		ret = db->seq(db, &key, &data, R_NEXT);
	}
	db->close(db);
}

static int
is_admin(const char *nick)
{
	hexchat_context *backup;
	hexchat_context *watch;
	hexchat_list *list;
	const char *op;
	int status = 0;

	backup = hexchat_get_context(ph);
	watch = hexchat_find_context(ph, NULL, watched_channel);
	if (watch != NULL) {
		hexchat_set_context(ph, watch);
		list = hexchat_list_get(ph, "users");
		if (list) {
			while(hexchat_list_next(ph, list)) {
				if (hexchat_nickcmp(ph, nick, hexchat_list_str(ph, list, "nick")) != 0)
					continue;

				op = hexchat_list_str(ph, list, "prefix");
				switch (*op) {
				case '*':
				case '!':
#if 0
				case '@': /* OP*/
#endif
				case '&':
				case '~':
					break;
				default:
					continue;
				}
				status = 1;
				break;
			}
			hexchat_list_free(ph, list);
		};
	};
	hexchat_set_context(ph, backup);
	return status;
}

static int
voice_user(const char *user)
{
	hexchat_context *backup;
	hexchat_context *watch;
	hexchat_list *list;
	int status = 0;

	backup = hexchat_get_context(ph);
	watch = hexchat_find_context(ph, NULL, watched_channel);
	if (watch != NULL) {
		hexchat_set_context(ph, watch);
		list = hexchat_list_get(ph, "users");
		if (list) {
			while(hexchat_list_next(ph, list)) {
				if (hexchat_nickcmp(ph, user, hexchat_list_str(ph, list, "nick")) != 0)
					continue;

				status = 1;
				hexchat_commandf(ph, "mode %s +v %s\n", watched_channel, user);
				break;
			}
			hexchat_list_free(ph, list);
		};
	};
	hexchat_set_context(ph, backup);
	return status;
}

static int
devoice_user(const char *user)
{
	hexchat_context *backup;
	hexchat_context *watch;
	hexchat_list *list;
	int status = 0;

	backup = hexchat_get_context(ph);
	watch = hexchat_find_context(ph, NULL, watched_channel);
	if (watch != NULL) {
		hexchat_set_context(ph, watch);
		list = hexchat_list_get(ph, "users");
		if (list) {
			while(hexchat_list_next(ph, list)) {
				if (hexchat_nickcmp(ph, user, hexchat_list_str(ph, list, "nick")) != 0)
					continue;

				status = 1;
				hexchat_commandf(ph, "mode %s -v %s\n", watched_channel, user);
				break;
			}
			hexchat_list_free(ph, list);
		};
	};
	hexchat_set_context(ph, backup);
	return status;
}

static void
check_devoice(const char *name)
{
	DB *db;
	DBT key, data;
	time_t now;
	time_t val;
	int ret;

	next_devoice = 0;
	db = dbopen(name, O_RDWR, 0600, DB_HASH, NULL);
	if (db == NULL) {
		if (errno == ENOENT)
			return;
		hexchat_printf(ph, "open database %s failed\n", name);
		return;
	};

	/* cleanup old entrys */
	now = time(NULL);
	ret = db->seq(db, &key, &data, R_FIRST);
	while (!ret) {
		if ((key.data == NULL) || (key.size <= 0) || (key.size >= sizeof(kbuf))) {
			hexchat_printf(ph, "database %s, oversized key\n", name);
			break;
		};
		if ((data.data == NULL) || (data.size <= 0) || (data.size >= sizeof(fbuf))) {
			hexchat_printf(ph, "database %s, oversized key\n", name);
			break;
		};

		strncpy(kbuf, key.data, key.size);
		kbuf[key.size] = 0;
		if (kbuf[key.size - 1] == '\n')
			kbuf[key.size - 1] = 0;
		strncpy(fbuf, data.data, data.size);
		fbuf[data.size] = 0;
		if (fbuf[data.size - 1] == '\n')
			fbuf[data.size - 1] = 0;

		val = atol(fbuf);
		if (val <= now) {
			devoice_user(kbuf);

			db->del(db, &key, 0);
			db->sync(db, 0);
			/* start over */
			ret = db->seq(db, &key, &data, R_FIRST);
			continue;
		};

		if ((next_devoice == 0) || (next_devoice > val))
			next_devoice = val;

		ret = db->seq(db, &key, &data, R_NEXT);
	}
	db->close(db);
	hexchat_printf(ph, "check_devoice() founds: %s", ctime(&next_devoice));
}

static int
timeout_cb(void *userdata)
{
	hexchat_context *backup;
	hexchat_context *watch;
        const char *str;
	char *data;
	int i;

	/* process queued buffer */
	if (notice_queue != NULL) {
		backup = hexchat_get_context(ph);
		watch = NULL;
		str = NULL;
		if (hexchat_get_prefs (ph, "irc_nick1", &str, &i) == 1)
			watch = hexchat_find_context(ph, NULL, str);
		if (watch == NULL)
			watch = hexchat_find_context(ph, NULL, watched_channel);
		if (watch != NULL) {
			data = queue_get(&notice_queue);
			if (data != NULL) {
				hexchat_set_context(ph, watch);
				hexchat_command(ph, data);
				free(data);
			};
		};
		hexchat_set_context(ph, backup);
	};

	if (next_devoice == 0)
		return 1;

	if (time(NULL) < next_devoice)
		return 1;

	check_devoice(voice_db);

	return 1; /* return 1 to keep the timeout going */
}

#if 0
	word	text

	1	:dinoex!~dinoex@euirc-c679c75c.dinoex.sub.de
	2	PRIVMSG
	3	dinoex
	4	:xdcc
	5	list | send
	6	group | pack
#endif

static void
extract_nick(const char *from)
{
	size_t len;
	char *end;

	nbuf[0] = 0;
	if (from == NULL)
		return;
	if (from[0] == 0)
		return;
	from ++;
	len = strlen(from);
	if ((len <= 0) || (len >= sizeof(nbuf))) {
		hexchat_printf(ph, "oversized nick %s\n", from);
		return;
	};
	strncpy(nbuf, from, len);
	nbuf[sizeof(nbuf) - 1] = 0;

	end = strchr(nbuf, '!');
	if (end == NULL)
		return;

	*end = 0;
	return;
}

static int
is_empty(const char *par)
{
	if (par == NULL)
		return 1;

	if (par[0] == 0)
		return 1;

	return 0;
}

static void
voice_admin(char *word[], char *word_eol[], void *userdata)
{
	const char *expires;
	time_t endtime;
	long zeit;
	int status;
	char buffer[20];
	char basis;

	if (is_empty(word[5]) != 0) {
		hexchat_commandf(ph,
			"notice %s Fehler. Kein Nick angegeben. "
			"Syntax: !voice <nick>[ <zeitraum>].\n",
			nbuf);
		return;
	};
	if (is_empty(word[6]) != 0) {
		status = voice_user(word[5]);
		if (status == 0) {
			hexchat_commandf(ph,
				"notice %s Fehler. \"%s\" ist nicht in %s.\n",
				nbuf, word[5], watched_channel);
			return;
		}
		hexchat_commandf(ph,
			"notice %s \"%s\" voiced in %s.\n",
			nbuf, word[5], watched_channel);
		return;
	};
	zeit = atol(word[6]);
	basis = word[6][strlen(word[6]) - 1];
	switch (basis) {
	case 's':
		break;
	case 'm':
		zeit *= 60;
		break;
	case 'h':
		zeit *= 3600;
		break;
	case 'd':
		zeit *= 86400L;
		break;
	case 'w':
		zeit *= 604800L;
		break;
	case 'y':
		zeit *= 31536000L;
		break;
	default:
		zeit = 0;
	}
	if (zeit <= 0) {
		hexchat_commandf(ph,
			"notice %s Fehler. Falsche Zeitangabe. "
			"Syntax: ist !voice <nick> <1-99999><s|m|h|d|w|y>.\n",
			nbuf);
		return;
	}

	expires = localdb_read(voice_db, word[5]);
	if (expires != NULL) {
		hexchat_commandf(ph,
			"notice %s Fehler. \"%s\" ist bereits in Liste vorhanden.\n",
			nbuf,  word[5]);
		return;
	};

	endtime = time(NULL) + zeit;
	snprintf(buffer, sizeof(buffer), "%lu", (unsigned long)endtime);
	localdb_write(voice_db, word[5], buffer);
	if ((next_devoice == 0) || (next_devoice > endtime))
		next_devoice = endtime;

	hexchat_commandf(ph,
		"notice %s \"%s\"  der Voice-Liste für %s hinzugefügt.\n",
		nbuf, word[5], word[6]);
	voice_user(word[5]);
}

static void
unvoice_admin(char *word[], char *word_eol[], void *userdata)
{
	const char *expires;

	if (is_empty(word[5]) != 0) {
		hexchat_commandf(ph,
			"notice %s Fehler. Kein Nick angegeben. "
			"Syntax: !unvoice <nick>.\n",
			nbuf);
		return;
	};
	expires = localdb_read(voice_db, word[5]);
	if (expires == NULL) {
		hexchat_commandf(ph,
			"notice %s Fehler. \"%s\" ist nicht in Liste vorhanden. Kann nicht löschen.\n",
			nbuf,  word[5]);
		return;
	};
	localdb_delete(voice_db, word[5]);
	hexchat_commandf(ph,
		"notice %s \"%s\" aus Voice-Liste entfernt.\n",
		nbuf,  word[5]);
	devoice_user(word[5]);
}

static void
vlist_admin(char *word[], char *word_eol[], void *userdata)
{
	localdb_list(voice_db);
	return;
}

static void
vinfo_admin(char *word[], char *word_eol[], void *userdata)
{
	const char *expires;
	time_t val;

	if (is_empty(word[5]) != 0) {
		hexchat_commandf(ph,
			"notice %s Voicler in Liste: %ld.\n",
			nbuf, localdb_info(voice_db));
		return;
	};
	if ((strcasecmp(word[5], "-all") == 0) || (strcasecmp(word[5], "-list") == 0)) {
		localdb_list(voice_db);
		return;
	};
	expires = localdb_read(voice_db, word[5]);
	if (expires == NULL) {
		hexchat_commandf(ph,
			"notice %s Fehler. \"%s\" ist nicht in Liste vorhanden.\n",
			nbuf,  word[5]);
		return;
	};
	val = atol(expires);
	hexchat_commandf(ph,
		"notice %s \"%s\" hat Voice bis: %s",
		nbuf, word[5], ctime(&val));
	/* (noch $duration($calc($hget(a-f_voice,$2) - $gmt)) */
}

static void
vhelp_admin(char *word[], char *word_eol[], void *userdata)
{
	if (is_empty(word[5]) != 0) {
		hexchat_commandf(ph,
			"notice %s (c) by Dinoex, Idee von squirrel. "
			"Weitere Informationen mit: %s <befehl>. "
			"Verfügbare Befehle: \"voice\", \"unvoice\", \"vinfo\", \"vlist\", \"vhelp\".\n",
			nbuf, &(word[4][2]));
		return;
	};
	if (strcasecmp(word[5], "voice") == 0) {
		hexchat_commandf(ph,
			"notice %s Fügt einen Nick zur Voice-liste hinzu. "
			"Syntax: !voice <nick>[ <zeitraum>]. "
			"Ohne \"<zeitraum>\" wird \"<nick>\" einmalig gevoiced, "
			"ohne Eintragung in Voice-Liste. "
			"\"<zeitraum>\" setzt sich zusammen aus Zahl von 1 - 99999 und "
			"entweder \"s\" (Sekunden), \"m\" (Minuten), \"d\" (Tage), \"w\" (Wochen) "
			"oder \"y\" (Jahre). Bsp: \"100m\", \"24h\", \"10w\", \"2y\".\n",
			nbuf);
		return;
	};
	if ( (strcasecmp(word[5], "unvoice") == 0) || (strcasecmp(word[5], "devoice") == 0) ) {
		hexchat_commandf(ph,
			"notice %s Entfernt einen Nick aus der Voice-Liste "
			"und devoiced (-v) ihn, falls er im Channel ist.\n",
			nbuf);
		return;
	};
	if (strcasecmp(word[5], "vlist") == 0) {
		hexchat_commandf(ph,
			"notice %s Gibt Alle Einträge der Voice-Liste aus.\n",
			nbuf);
		return;
	};
	if (strcasecmp(word[5], "vinfo") == 0) {
		hexchat_commandf(ph,
			"notice %s Gibt Informationen über Voice-Liste wieder. "
			"\"!vinfo\" gibt Größe der Voice-Liste an. "
			"\"!vinfo -list\" oder \"!vinfo -all\" gibt alle Einträge der Voice-Liste aus. "
			"\"!vinfo <nick>\" oder \"!vinfo <id>\" gibt Informationen über den Nick \"<nick>\" "
			"bzw. den Eintrag mit der ID \"<id>\" an.\n",
			nbuf);
		return;
	};
	if ( (strcasecmp(word[5], "vhelp") == 0) || (strcasecmp(word[5], "voicehelp") == 0) ) {
		hexchat_commandf(ph,
			"notice %s Gibt verfügbare Befehle aus.\n",
			nbuf);
		return;
	};
	hexchat_commandf(ph,
		"notice %s Fehler. Angegebener Befehl existiert nicht.\n",
		nbuf);
}


static int
voice_command(char *word[], char *word_eol[], void *userdata)
{
	int admin;

	admin = is_admin(nbuf);

	if (strcasecmp(word[4], ":!voice") == 0) {
		if (admin == 0) {
			hexchat_commandf(ph, "notice %s Fehler. Du hast keinen Admin-Status in %s.",
				nbuf, watched_channel);
		} else {
			voice_admin(word, word_eol, userdata);
		}
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
	};
	if ( (strcasecmp(word[4], ":!unvoice") == 0) || (strcasecmp(word[4], ":!devoice") == 0) ) {
		if (admin == 0) {
			hexchat_commandf(ph, "notice %s Fehler. Du hast keinen Admin-Status in %s.",
				nbuf, watched_channel);
		} else {
			unvoice_admin(word, word_eol, userdata);
		}
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
	};
	if (strcasecmp(word[4], ":!vlist") == 0) {
		if (admin == 0) {
			hexchat_commandf(ph, "notice %s Fehler. Du hast keinen Admin-Status in %s.",
				nbuf, watched_channel);
		} else {
			vlist_admin(word, word_eol, userdata);
		}
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
	};
	if (strcasecmp(word[4], ":!vinfo") == 0) {
		if (admin == 0) {
			hexchat_commandf(ph, "notice %s Fehler. Du hast keinen Admin-Status in %s.",
				nbuf, watched_channel);
		} else {
			vinfo_admin(word, word_eol, userdata);
		}
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
	};
	if ( (strcasecmp(word[4], ":!vhelp") == 0) || (strcasecmp(word[4], ":!voicehelp") == 0) ) {
		if (admin == 0) {
			hexchat_commandf(ph, "notice %s Fehler. Du hast keinen Admin-Status in %s.",
				nbuf, watched_channel);
		} else {
			vhelp_admin(word, word_eol, userdata);
		}
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
	};
	return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
}

static int
voice_context(char *word[], char *word_eol[], void *userdata)
{
	hexchat_context *backup;
	hexchat_context *watch;
	int rc;

	extract_nick(word[1]);
	rc = HEXCHAT_EAT_NONE;
	backup = hexchat_get_context(ph);
	watch = hexchat_find_context(ph, NULL, nbuf);
	if (watch == NULL)
		watch = hexchat_find_context(ph, NULL, watched_channel);
	if (watch != NULL)
		rc = voice_command(word, word_eol, userdata);
	hexchat_set_context(ph, backup);
	return rc;
}

static int
privmsg_cb(char *word[], char *word_eol[], void *userdata)
{
        const char *str;
	int i;

	if (enable == 0)
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

	if (strcasecmp(word[3], watched_channel) == 0) {
		if (word[4][1] != '!')
			return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

		return voice_context(word, word_eol, userdata);
	}

	str = NULL;
	if (hexchat_get_prefs (ph, "irc_nick1", &str, &i) == 1) {
		if (hexchat_nickcmp(ph,word[3], str) == 0) {
			return voice_context(word, word_eol, userdata);
		}
	}
	return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
}

static int
join_cb(char *word[], void *userdata)
{
	const char *expires;
	char *lower;
	time_t val;

	if (enable == 0)
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

	if (strcasecmp(word[2], watched_channel) != 0)
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

#if 0
	1	Nick
	2	Chan
	3	Ident
#endif

	expires = localdb_read(voice_db, word[1]);
	if (expires == NULL) {
		lower = strdup(word[1]);
		if (lower == NULL)
			return HEXCHAT_EAT_NONE;
		string_to_lowercase(lower);
		expires = localdb_read(voice_db, lower);
		free(lower);
		if (expires == NULL) {
			return HEXCHAT_EAT_NONE;
		}
	}

	val = atol(expires);
	if (val <= time(NULL)) {
		localdb_delete(voice_db, word[1]);
	} else {
		hexchat_commandf(ph, "mode %s +v %s\n", watched_channel, word[1]);
	}
	return HEXCHAT_EAT_NONE;  /* don't eat this event, hexchat needs to see it! */
}
     
static void
timer_end(void)
{
	if (timerhook == NULL)
		return;

	hexchat_unhook(ph, timerhook);
	timerhook = NULL;
}

static void
timer_start(void)
{
	if (timerhook == NULL)
		timerhook = hexchat_hook_timer(ph, 1000, timeout_cb, NULL);
}

static int
voice_toggle_cb(char *word[], char *word_eol[], void *userdata)
{
	if (enable == 0) {
		enable = 1;
		timer_start();
		hexchat_print(ph, "avoice now enabled!\n");
	} else {
		enable = 0;
		queue_delete(&notice_queue);
		timer_end();
		hexchat_print(ph, "avoice now disabled!\n");
	}

	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

int
hexchat_plugin_init(hexchat_plugin *plugin_handle,
	const char **plugin_name,
	const char **plugin_desc,
	const char **plugin_version,
	const char *arg)
{
	const char *cptr;
	const char *chan;

	/* we need to save this for use with any hexchat_* functions */
	ph = plugin_handle;

	*plugin_name = "avoice";
	*plugin_desc = "auto voice bot";
	*plugin_version = "0.6";

	cptr = hexchat_get_info(ph, "xchatdirfs");
	if (cptr == NULL)
		cptr = ".";
	configdir = strdup(cptr);
	snprintf(fbuf, sizeof(fbuf), "%s/avoice.db", configdir);
	voice_db = strdup(fbuf);
	snprintf(fbuf, sizeof(fbuf), "%s/aoptions.db", configdir);
	options_db = strdup(fbuf);

	chan = localdb_read(options_db, "chanel");
	if (chan != NULL)
		watched_channel = chan;

	hexchat_hook_command(ph, "avoice", HEXCHAT_PRI_NORM, voice_toggle_cb,
		"Usage: avoice, Turns OFF/ON avoice", 0);

	hexchat_hook_server(ph, "PRIVMSG", HEXCHAT_PRI_NORM, privmsg_cb, NULL);
	hexchat_hook_print(ph, "Join", HEXCHAT_PRI_NORM, join_cb, 0);

	timerhook = NULL;
	timer_start();

	hexchat_printf(ph, "%s Plugin %s loaded successfully!\n", *plugin_name, *plugin_version);

	next_devoice = time(NULL);

	return 1; /* return 1 for success */
}

void
hexchat_plugin_deinit(void)
{
	queue_delete(&notice_queue);
	if (configdir != NULL)
		free(configdir);
	if (voice_db != NULL)
		free(voice_db);
	if (options_db != NULL)
		free(options_db);
}

/* EOF */
