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

 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.

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

	botlist - a plugin for hexchat2
	===========================

	$Id: botlist.c,v 1.13 2008/11/08 20:07:58 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

#include <regex.h>

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
#define MAX_WORD 15

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

typedef struct _botlist_entry {
	char *s_trigger;
	char *s_command;
	regex_t *s_regexp;
} botlist_entry;


static hexchat_plugin *ph; /* plugin handle */
static hexchat_hook *timerhook_sec = NULL;
static hexchat_hook *timerhook_min = NULL;
static hexchat_hook *timerhook_hrs = NULL;
static int enable = 1;
static int botlist_list_count = 0;
static int botlist_exclude_count = 0;
static char *configdir = NULL;
static char *botlist_config = NULL;
static char *botlist_db = NULL;
static char *botlist_export = NULL;
static char *watched_channel = NULL;
static char *watched_bot = NULL;
static char *watched_master = NULL;
static queue_entry *notice_queue = NULL;
static queue_entry *whois_queue = NULL;
static botlist_entry botlist_list[ MAX_BUF ];
static char *botlist_exclude_channel[ MAX_BUF ];
static char fbuf[MAX_BUF];
static char qbuf[MAX_BUF];
static char nbuf[MAX_BUF];
static char kbuf[MAX_BUF];
static char cbuf[MAX_BUF];


static void
null_free(char **data)
{
	if (*data == NULL)
		return;
	free(*data);
	*data = NULL;
}

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 void
localdb_list(const char *name)
{
	DB *db;
	DBT key, data;
	int ret;
	char *channel;
	long valid;
	long sec;

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

	valid = time(NULL) - ( 60 * 60 * 24 );
	/* cleanup old entrys */
	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;

		channel = strchr(fbuf, ' ');
		if (channel != NULL) {
			*(channel++)= 0;
			sec = atol(fbuf);
			if (sec < valid) {
				queue_addf(&notice_queue, "notice dinoex %s is offline %s", kbuf, fbuf);
			}
		}
		ret = db->seq(db, &key, &data, R_NEXT);
	}
	db->close(db);
}

static void
localdb_check(const char *name)
{
	DB *db;
	DBT key, data;
	int ret;
	char *channel;
	char *master;
	long valid;
	long sec;

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

	valid = time(NULL) - ( 60 * 60 * 24 );
	/* cleanup old entrys */
	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;
		channel = strchr(fbuf, ' ');
		if (channel != NULL) {
			*(channel++)= 0;
			sec = atol(fbuf);
			if (sec < valid) {
				master = strchr(channel, ' ');
				if (master != NULL) {
					*(master++)= 0;
				} else {
					master = channel + strlen(channel);
				}
#if DEBUG
				hexchat_printf(ph, "botlist: whois %s in %s on %s\n", kbuf, channel, master);
#endif
				queue_addf(&whois_queue, "%s %s whois %s", master, channel, kbuf);
			}
		}
		ret = db->seq(db, &key, &data, R_NEXT);
	}
	db->close(db);
}

static void
botlist_clean(void)
{
	int i;

	null_free(&watched_channel);
	null_free(&watched_bot);
	null_free(&watched_master);
	for ( i = 0; i < botlist_list_count; i++ ) {
		free(botlist_list[ i ].s_trigger);
		free(botlist_list[ i ].s_command);
		free(botlist_list[ i ].s_regexp);
	}
	botlist_list_count = 0;
	for ( i = 0; i < botlist_exclude_count; i++ ) {
		free(botlist_exclude_channel[ i ]);
	}
	botlist_exclude_count = 0;
}

static int
botlist_update(void)
{
	FILE *fp;
	char *data;
	char *nl;
	char *pattern;
	int found = 0;
	int rc;

	botlist_clean();

	fp = fopen(botlist_config, "r");
	if (fp == NULL) {
		hexchat_printf(ph, "botlist cant read: %s\n", botlist_config);
		return found;
	}
	while (!feof(fp)) {
		data = fgets(fbuf, sizeof(fbuf) -1, fp);
		if (data == NULL) {
			/* no data */
			break;
		}
		nl = strchr(data, '\n');
		if (nl != NULL) *nl = 0;
		if (data[0] == '#') {
			watched_channel = strdup( data );
			continue;
		}
		if (data[0] == '!') {
			if  (botlist_exclude_count >= MAX_BUF) {
				hexchat_printf(ph, "to many lines\n");
				break;
			}
			botlist_exclude_channel[ botlist_exclude_count ] = strdup( data + 1 );
			botlist_exclude_count ++;
			continue;
		}
		if (++found >= MAX_BUF) {
			hexchat_printf(ph, "to many lines\n");
			break;
		}
		pattern = strchr(data, '|');
		if (pattern == NULL)
			continue;
		*(pattern++) = 0;
		nl = strchr(pattern, '|');
		if (nl != NULL) *nl = 0;
		botlist_list[ botlist_list_count ].s_command = strdup( data );
		botlist_list[ botlist_list_count ].s_trigger = strdup( pattern );
		botlist_list[ botlist_list_count ].s_regexp = calloc(1, sizeof(regex_t));
		rc = regcomp( botlist_list[ botlist_list_count ].s_regexp, botlist_list[ botlist_list_count ].s_trigger, REG_ICASE|REG_NOSUB);
		hexchat_printf(ph, "botlist trigger <%s> action: %s, %d\n", pattern, data, rc);
		botlist_list_count ++;
	}
	fclose(fp);
	hexchat_printf(ph, "Loaded %d triggers for botlist\n", found );
	return found;
}

static int
timeout_sec_cb(void *userdata)
{
	hexchat_context *backup;
	hexchat_context *watch;
	char *data;

	/* process queued buffer */
	if (notice_queue != NULL) {
		backup = hexchat_get_context(ph);
		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);
	};
	return 1; /* return 1 to keep the timeout going */
}

static int
timeout_min_cb(void *userdata)
{
	hexchat_context *backup;
	hexchat_context *watch;
	char *data;
	char *master;
	char *channel;
	char *cmd;
	char *bot;

	/* process queued buffer */
	if (whois_queue != NULL) {
		data = queue_get(&whois_queue);
		if (data != NULL) {
			master = data;
			channel = strchr(data, ' ');
			if (channel != NULL)
				*(channel++) = 0;
			null_free(&watched_bot);
			null_free(&watched_master);
			cmd = strchr(channel, ' ');
			if (strlen(master) == 0)
				master = NULL;
			if (cmd != NULL)
				*(cmd++) = 0;
			bot = strchr(cmd, ' ');
			if (bot != NULL)
				bot++;
			backup = hexchat_get_context(ph);
			watch = hexchat_find_context(ph, NULL, master);
			if (watch == NULL) {
				watch = hexchat_find_context(ph, NULL, channel);
				master = channel;
			}
			if (watch == NULL) {
				watch = hexchat_find_context(ph, NULL, watched_channel);
				master = watched_channel;
			}
			if ((watch != NULL) && (cmd != NULL)) {
				hexchat_set_context(ph, watch);
#if DEBUG
				hexchat_printf(ph, "botlist: run %s in %s on %s for %s\n", cmd, channel, master, bot);
#endif
				if (master!= NULL)
				watched_master = strdup(master);
				if (bot!= NULL)
				watched_bot = strdup(bot);
				hexchat_command(ph, cmd);
			};
			free(data);
			hexchat_set_context(ph, backup);
		};
	};
	return 1; /* return 1 to keep the timeout going */
}

static int
timeout_hrs_cb(void *userdata)
{
	localdb_check(botlist_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 void
botlist_seen(const char *nick, const char *channel, const char *master, long val)
{
	int i;

	if (channel == NULL) {
		channel = hexchat_get_info(ph, "channel");
		if (channel == NULL) {
			hexchat_printf(ph, "No channel found for nick %s\n", nick);
			return;
		}
		for ( i = 0; i < botlist_exclude_count; i++ ) {
			if (botlist_exclude_channel[ i ][ 0 ] == '#') {
				if (strcasecmp(channel, botlist_exclude_channel[ i ]) == 0) {
					return;
				}
			}
		}
	}
	for ( i = 0; i < botlist_exclude_count; i++ ) {
		if (botlist_exclude_channel[ i ][ 0 ] != '#') {
			if (strcasecmp(nick, botlist_exclude_channel[ i ]) == 0) {
				return;
			}
		}
	}
	if (master == NULL)
		master = channel;
	snprintf(cbuf, sizeof(cbuf), "%ld %s %s", val, channel, master);
	localdb_write(botlist_db, nick, cbuf);
	return;
}

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

	for ( i = 0; i < botlist_list_count; i++ ) {
		if (regexec(botlist_list[ i ].s_regexp, word_eol[4], 0, NULL, 0) == 0) {
			if (strcasestr(word_eol[4], nbuf) != NULL) { 
				botlist_seen(nbuf, NULL, NULL, time(NULL));
#if 0
				queue_addf(&notice_queue, "notice dinoex %s: %s", nbuf, word_eol[4] );
#endif
				return;
			}
		}
	}
}


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

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

	if (word[4] == NULL)
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

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

static int
drop_cb(char *word[], char *word_eol[], void *userdata)
{
	if (watched_bot == NULL)
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

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

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

static int
whois2_cb(char *word[], char *word_eol[], void *userdata)
{
	const char *old;

	old = localdb_read(botlist_db, word[4]);
	if (old == NULL)
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

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

	if (strcmp(word[4], watched_bot) != 0 ) {
		hexchat_printf(ph, "botlist: check %s <-> %s\n", word[4], watched_bot);
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
        }

	botlist_seen(word[4], "hidden", watched_master, time(NULL));
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

/* <nick> :*( ( '@' / '+' ) <channel> ' ' ) */

static int
whois_cb(char *word[], char *word_eol[], void *userdata)
{
	const char *old;
	const char *channel;
	const char *test;
	int i;
	int j;
	int skip;

	old = localdb_read(botlist_db, word[4]);
	if (old == NULL)
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */

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

	if (strcmp(word[4], watched_bot) != 0 ) {
		hexchat_printf(ph, "botlist: check %s <-> %s\n", word[4], watched_bot);
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
        }

	channel = NULL;
	for (i=5; i<MAX_WORD; i++) {
		test = word[i];
		if (test == NULL)
			break;
		if (strcmp(word[i], word_eol[i]) == 0 )
			i = MAX_WORD; /* force end on next loop */
		while (*test == ':') ++test;
		while (*test == '*') ++test;
		while (*test == '@') ++test;
		while (*test == '%') ++test;
		while (*test == '+') ++test;
		while (*test == '~') ++test;
		while (*test == '!') ++test;
		while (*test == '&') ++test;
		if (*test == 0)
			continue;
		if (*test != '#') {
			hexchat_printf(ph, "botlist: bad channel in whois: %s\n", test);
			break;
		}
		if (channel != NULL) {
			skip = 0;
			for ( j = 0; j < botlist_exclude_count; j++ ) {
				if (botlist_exclude_channel[ j ][ 0 ] == '#') {
					if (strcasecmp(test, botlist_exclude_channel[ j ]) == 0) {
						skip ++;
						break;
					}
				}
			}
			if (skip > 0)
				continue;
		}
		channel = test;
	}

	if (channel == NULL) {
		hexchat_printf(ph, "botlist: no channel in whois: %s\n", word_eol[4]);
		return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
	}
	botlist_seen(word[4], channel, watched_master, time(NULL));
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

static int
botlistupdate_cb(char *word[], char *word_eol[], void *userdata)
{
	botlist_update();
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

static int
botshow_cb(char *word[], char *word_eol[], void *userdata)
{
	localdb_list(botlist_db);
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

static int
botwhois_cb(char *word[], char *word_eol[], void *userdata)
{
	localdb_check(botlist_db);
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

static int
botadd_cb(char *word[], char *word_eol[], void *userdata)
{
	const char *old;

	if (word[2] == NULL) {
		hexchat_print(ph, "missing nickname!\n");
		return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
	}
	old = localdb_read(botlist_db, word[2]);
	botlist_seen(word[2], NULL, NULL, 0);
	if (old == NULL) {
		hexchat_printf(ph, "nickname %s added.\n", word[2]);
	} else {
		hexchat_printf(ph, "nickname %s changed.\n", word[2]);
	}
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

static int
botdel_cb(char *word[], char *word_eol[], void *userdata)
{
	const char *old;

	if (word[2] == NULL) {
		hexchat_print(ph, "missing nickname!\n");
		return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
	}
	old = localdb_read(botlist_db, word[2]);
	if (old == NULL) {
		hexchat_printf(ph, "nickname %s not found in db.\n", word[2]);
		return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
	}
	localdb_delete(botlist_db, word[2]);
	hexchat_printf(ph, "nickname %s removed.\n", word[2]);
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process it */
}

static void
timer_end(void)
{
	if (timerhook_sec != NULL) {
		hexchat_unhook(ph, timerhook_sec);
		timerhook_sec = NULL;
	}
	if (timerhook_min != NULL) {
		hexchat_unhook(ph, timerhook_min);
		timerhook_min = NULL;
	}
	if (timerhook_hrs != NULL) {
		hexchat_unhook(ph, timerhook_hrs);
		timerhook_hrs = NULL;
	}
}

static void
timer_start(void)
{
	if (timerhook_sec == NULL)
		timerhook_sec = hexchat_hook_timer(ph, 1000, timeout_sec_cb, NULL);
	if (timerhook_min == NULL)
		timerhook_min = hexchat_hook_timer(ph, 60 * 1000, timeout_min_cb, NULL);
	if (timerhook_hrs == NULL)
		timerhook_hrs = hexchat_hook_timer(ph, 60 * 60 * 1000, timeout_hrs_cb, NULL);
}

static int
botlist_toggle_cb(char *word[], char *word_eol[], void *userdata)
{
	if (enable == 0) {
		enable = 1;
		timer_start();
		hexchat_print(ph, "botlist now enabled!\n");
		botlist_update();
	} else {
		enable = 0;
		queue_delete(&notice_queue);
		queue_delete(&whois_queue);
		timer_end();
		hexchat_print(ph, "botlist 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;

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

	*plugin_name = "botlist";
	*plugin_desc = "botlist extensions";
	*plugin_version = "0.4";

	cptr = hexchat_get_info(ph, "xchatdirfs");
	if (cptr == NULL)
		cptr = ".";
	configdir = strdup(cptr);
	snprintf(fbuf, sizeof(fbuf), "%s/botlist.config", configdir);
	botlist_config = strdup(fbuf);
	snprintf(fbuf, sizeof(fbuf), "%s/botlist.db", configdir);
	botlist_db = strdup(fbuf);
	snprintf(fbuf, sizeof(fbuf), "%s/botlist.txt", configdir);
	botlist_export = strdup(fbuf);

	hexchat_hook_command(ph, "botlist", HEXCHAT_PRI_NORM, botlist_toggle_cb,
		"Usage: botlist, Turns OFF/ON botlist", 0);
	hexchat_hook_command(ph, "botlistupdate", HEXCHAT_PRI_NORM, botlistupdate_cb,
		"Usage: botlistupdate, read config", 0);
	hexchat_hook_command(ph, "botshow", HEXCHAT_PRI_NORM, botshow_cb,
		"Usage: botshow, show bots", 0);
	hexchat_hook_command(ph, "botadd", HEXCHAT_PRI_NORM, botadd_cb,
		"Usage: botadd, add a bot", 0);
	hexchat_hook_command(ph, "botdel", HEXCHAT_PRI_NORM, botdel_cb,
		"Usage: botdel nick, remove a bot", 0);
	hexchat_hook_command(ph, "botwhois", HEXCHAT_PRI_NORM, botwhois_cb,
		"Usage: botwhois, check for offline bots", 0);

	hexchat_hook_server(ph, "PRIVMSG", HEXCHAT_PRI_NORM, privmsg_cb, NULL);
	hexchat_hook_server(ph, "NOTICE", HEXCHAT_PRI_NORM, privmsg_cb, NULL);
	hexchat_hook_server(ph, "311", HEXCHAT_PRI_NORM, drop_cb, NULL);
	hexchat_hook_server(ph, "312", HEXCHAT_PRI_NORM, drop_cb, NULL);
	hexchat_hook_server(ph, "313", HEXCHAT_PRI_NORM, drop_cb, NULL);
	hexchat_hook_server(ph, "314", HEXCHAT_PRI_NORM, drop_cb, NULL);
	hexchat_hook_server(ph, "315", HEXCHAT_PRI_NORM, drop_cb, NULL);
	hexchat_hook_server(ph, "317", HEXCHAT_PRI_NORM, drop_cb, NULL);
	hexchat_hook_server(ph, "318", HEXCHAT_PRI_NORM, drop_cb, NULL);
	hexchat_hook_server(ph, "319", HEXCHAT_PRI_NORM, whois_cb, NULL);
	hexchat_hook_server(ph, "335", HEXCHAT_PRI_NORM, whois2_cb, NULL);

	timerhook_sec = NULL;
	timerhook_min = NULL;
	timer_start();

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

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

void
hexchat_plugin_deinit(void)
{
	queue_delete(&notice_queue);
	queue_delete(&whois_queue);
	null_free(&configdir);
	null_free(&botlist_config);
	null_free(&botlist_db);
	null_free(&botlist_export);
	botlist_clean();
}

/* EOF */
