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

 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.

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

	xdccserver - a plugin for xchat2
	================================

	$Id: xdccserver.c,v 1.14 2006/08/03 09:19:01 dm Exp $

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

#include "xchat-plugin.h"

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

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


int xchat_plugin_init(xchat_plugin *plugin_handle,
	const char **plugin_name,
	const char **plugin_desc,
	const char **plugin_version,
	const char *arg);
void xchat_plugin_deinit(void);


#define	MAX_BUF	1024


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


static xchat_plugin *ph; /* plugin handle */
static xchat_hook *timerhook = NULL;
static int enable = 1;
static char *configdir = NULL;
static char *xdccshared = NULL;
static char *xdccoption = NULL;
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 queue_entry *
queue_init(const char *data)
{
	queue_entry *new;

	new = malloc(sizeof(queue_entry));
	if (new == NULL) {
		xchat_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;
		xchat_printf(ph, "open database %s failed\n", name);
		return NULL;
	}

	/* generate entry */
	hash2 = strdup(hash);
	if (hash2 == NULL) {
		xchat_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 {
			xchat_printf(ph, "database %s, get failed, size = %d\n", name, data.size);
		}
	} else {
		if (rc != 1)
			xchat_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) {
		xchat_printf(ph, "open database %s failed\n", name);
		return;
	}

	/* lock all changes */
	fd = db->fd(db);
	if (fd == -1) {
		st = -1;
		xchat_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) {
			xchat_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))
			xchat_printf(ph, "database %s, delete returns %d\n", name, rc);
		db->sync(db,0);
		free(hash2);
		st = flock(fd, LOCK_UN);
	} else {
		xchat_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) {
		xchat_printf(ph, "open database %s failed\n", name);
		return;
	}

	/* lock all changes */
	fd = db->fd(db);
	if (fd == -1) {
		st = -1;
		xchat_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) {
			xchat_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))
			xchat_printf(ph, "database %s, write returns %d\n", name, rc);
		db->sync(db,0);
		free(hash2);
		st = flock(fd, LOCK_UN);
	} else {
		xchat_printf(ph, "database %s, lock failed\n", name);
	}
	db->close(db);
}

static void
localdb_list(const char *name, const char *nick, const char *show)
{
	DB *db;
	DBT key, data;
	char *basename;
	const char *match;
	int ret;

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

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

		basename = strrchr(fbuf, '/');
		if (basename != NULL)
			basename++;
		else
			basename = fbuf;

		match = basename;
		for (;;) {
			if (show == NULL)
				break;
			if (strlen(show) <= 0)
				break;
			match = strcasestr(basename, show);
			break;
		}
	
		if (match != NULL) {
			queue_addf(&notice_queue, "notice %s #%s %s", nick, kbuf, basename);
		}

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

static int timeout_cb(void *userdata)
{
	char *data;

	/* process queued buffer */
	if (notice_queue != NULL) {
		data = queue_get(&notice_queue);
		if (data != NULL ) {
			xchat_command(ph, data);
			free(data);
		}
	};

	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))) {
		xchat_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
xdcc_list(char *word[], char *word_eol[], void *userdata, const char *server)
{
	int i;
	const char *str;

	extract_nick(word[1]);
	if (server == NULL)
		server = "<nick>";

	queue_addf(&notice_queue, "notice %s request files with /msg %s xdcc send #pack", nbuf, server);
	queue_addf(&notice_queue, "notice %s see details with /msg %s xdcc info #pack", nbuf, server);

	localdb_list(xdccshared, nbuf, word[6]);
}

static void
xdcc_send(char *word[], char *word_eol[], void *userdata)
{
	const char *file;
	char *pack;

	extract_nick(word[1]);
	pack = word[6];
	if (pack[0] == '#')
		pack ++;

	file = localdb_read(xdccshared, pack);
	if (file == NULL) {
		xchat_commandf(ph, "notice %s pack %s not found.", nbuf, pack);
		return;
	}
	xchat_commandf(ph, "dcc send %s %s", nbuf, file);
}

static void
xdcc_info(char *word[], char *word_eol[], void *userdata)
{
	const char *file;
	char *pack;
	char *end;
	char *line;
	size_t len;
	FILE *fd;

	extract_nick(word[1]);
	pack = word[6];
	if (pack[0] == '#')
		pack ++;

	file = localdb_read(xdccshared, pack);
	if (file == NULL) {
		xchat_commandf(ph, "notice %s pack %s not found.", nbuf, pack);
		return;
	}
	for (;;) {
		end = strchr(file, '.');
		if (end == NULL)
			break;
		strcpy(end, ".txt");
		fd = fopen(file, "ra");
		if (fd == NULL)
			break;

		for (;;) {
			line = fgets(fbuf, sizeof(fbuf) - 1, fd);
			if (line == NULL)
				break;
			strncpy(fbuf, line, sizeof(fbuf) - 1);
			fbuf[sizeof(fbuf)] = 0;
			len = strlen(fbuf);
			if (fbuf[len - 1] == '\n')
				fbuf[len - 1] = 0;
			len = strlen(fbuf);
			if (len == 0)
				strcpy(fbuf, "." );
			queue_addf(&notice_queue, "notice %s %s", nbuf, fbuf);
		}
		fclose(fd);
		return;
	}
	xchat_commandf(ph, "notice %s pack %s has no info.", nbuf, pack);
}

static void
xdcc_channel_list(char *word[], char *word_eol[], void *userdata, const char *server)
{
	const char *file;

	extract_nick(word[1]);

	file = localdb_read(xdccoption, word[3]);
	if (file == NULL)
		return;

	if (strcasestr(file, "respond") == NULL)
		return;

	if (server == NULL)
		server = "<nick>";
	queue_addf(&notice_queue, "privmsg %s see list with /msg %s xdcc list", nbuf, server);
}

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

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

	str = NULL;
	if (xchat_get_prefs (ph, "irc_nick1", &str, &i) == 1) {
		if (xchat_nickcmp(ph,word[3], str) != 0) {
			if (strcasecmp(word[4], ":!list") == 0) {
				xdcc_channel_list(word, word_eol, userdata, str);
			}
			return XCHAT_EAT_NONE; /* don't eat this event, let other plugins and xchat see it too */
		}
	}

	if (strcasecmp(word[4], ":xdcc") != 0)
		return XCHAT_EAT_NONE; /* don't eat this event, let other plugins and xchat see it too */

	if (strcasecmp(word[5], "list") == 0) {
		xdcc_list(word, word_eol, userdata, str);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	if (strcasecmp(word[5], "send") == 0) {
		xdcc_send(word, word_eol, userdata);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	if (strcasecmp(word[5], "info") == 0) {
		xdcc_info(word, word_eol, userdata);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	xchat_printf(ph, "1: %s 2: %s 3: %s 4: %s (more=%s)\n",
		word[1], word[2], word[3], word[4], word_eol[5]);
	return XCHAT_EAT_NONE; /* don't eat this event, let other plugins and xchat see it too */
}

static int
notice_cb(char *word[], char *word_eol[], void *userdata)
{
	return XCHAT_EAT_NONE; /* don't eat this event, let other plugins and xchat see it too */
}

static int
xdcclist_cb(char *word[], char *word_eol[], void *userdata)
{
	xchat_list *list;
	int status;

	list = xchat_list_get(ph, "dcc");
	if(list)
	{
		xchat_print(ph, "--- DCC LIST ------------------\n"
				"File  To/From   KB/s   Position\n");

		while(xchat_list_next(ph, list))
		{
			status = xchat_list_int(ph, list, "status");
			if (status > 1)
				continue;

			xchat_printf(ph, "%6s %10s %.2f  %d\n",
				xchat_list_str(ph, list, "file"),
				xchat_list_str(ph, list, "nick"),
				(float)(xchat_list_int(ph, list, "cps") / 1024),
				xchat_list_int(ph, list, "pos"));
		}
		xchat_list_free(ph, list);
	}
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

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

	file = localdb_read(xdccshared, word[2]);
	if (file == NULL) {
		xchat_printf(ph, "xdccserver: pack %s not found.\n", word[2]);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	localdb_delete(xdccshared, word[2]);
	xchat_printf(ph, "xdccserver: pack %s removed.\n", word[2]);
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

static int
xdccadd_cb(char *word[], char *word_eol[], void *userdata)
{
	const char *file;
	int fd;

	file = localdb_read(xdccshared, word[2]);
	if (file != NULL) {
		xchat_printf(ph, "xdccserver: pack %s exists.\n", word[2]);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	fd = open(word[3], O_RDONLY);
	if (fd == NULL) {
		xchat_printf(ph, "xdccserver: pack %s, file %s not found.\n", word[2], word[3]);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	close(fd);

	localdb_write(xdccshared, word[2], word_eol[3]);
	xchat_printf(ph, "xdccserver: pack %s added.\n", word[2]);
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

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

	file = localdb_read(xdccoption, word[2]);
	if (file == NULL) {
		xchat_printf(ph, "xdccserver: pack %s not found.\n", word[2]);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	localdb_delete(xdccoption, word[5]);
	xchat_printf(ph, "xdccserver: pack %s removed.\n", word[2]);
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

static int
xdccenable_cb(char *word[], char *word_eol[], void *userdata)
{
	const char *file;
	int fd;

	file = localdb_read(xdccoption, word[2]);
	if (file != NULL) {
		xchat_printf(ph, "xdccserver: pack %s exists.\n", word[2]);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	fd = open(word[3], O_RDONLY);
	if (fd == NULL) {
		xchat_printf(ph, "xdccserver: pack %s, file %s not found.\n", word[2], word[3]);
		return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
	}
	close(fd);

	localdb_write(xdccoption, word[2], word_eol[3]);
	xchat_printf(ph, "xdccserver: pack %s added.\n", word[2]);
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

static void
timer_end(void)
{
	if (timerhook == NULL)
		return;

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

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

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

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

int
xchat_plugin_init(xchat_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 xchat_* functions */
	ph = plugin_handle;

	*plugin_name = "xdccserver";
	*plugin_desc = "xdcc file server bot";
	*plugin_version = "0.2";

	cptr = xchat_get_info(ph, "xchatdirfs");
	if (cptr == NULL)
		cptr = ".";
	configdir = strdup(cptr);
	snprintf(fbuf, sizeof(fbuf), "%s/shared.db", configdir);
	xdccshared = strdup(fbuf);
	snprintf(fbuf, sizeof(fbuf), "%s/options.db", configdir);
	xdccoption = strdup(fbuf);

	xchat_hook_command(ph, "xdccserver", XCHAT_PRI_NORM, xdccserver_toggle_cb,
		"Usage: xdccserver, Turns OFF/ON file server", 0);
	xchat_hook_command(ph, "xdcclist", XCHAT_PRI_NORM, xdcclist_cb,
		"Usage: xdcclist, list all active DCC transfers", 0);
	xchat_hook_command(ph, "xdccdel", XCHAT_PRI_NORM, xdccdel_cb,
		"Usage: xdccdel pack, remove a pack from list of shared files", 0);
	xchat_hook_command(ph, "xdccadd", XCHAT_PRI_NORM, xdccadd_cb,
		"Usage: xdccadd pack filename, add a pack to the shared files", 0);
	xchat_hook_command(ph, "xdccdisable", XCHAT_PRI_NORM, xdccdisable_cb,
		"Usage: xdccdisable #chan, don't respond in this channel", 0);
	xchat_hook_command(ph, "xdccenable", XCHAT_PRI_NORM, xdccenable_cb,
		"Usage: xdccenable #chan options, respond in this channel", 0);

	xchat_hook_server(ph, "PRIVMSG", XCHAT_PRI_NORM, privmsg_cb, NULL);
	xchat_hook_server(ph, "NOTICE", XCHAT_PRI_NORM, notice_cb, NULL);

	timerhook = NULL;
	timer_start();

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

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

void
xchat_plugin_deinit(void)
{
	queue_delete(&notice_queue);
	if (configdir != NULL)
		free(configdir);
	if (xdccshared != NULL)
		free(xdccshared);
	if (xdccoption != NULL)
		free(xdccoption);
}

/* EOF */
