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

 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.

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

	solver - a plugin for hexchat2
	=====)======================

	$Id: solver.c,v 1.8 2007/05/25 11:10:56 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	4096

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

typedef struct _solver_entry {
	char *s_trigger;
	char *s_command;
} solver_entry;


static hexchat_plugin *ph; /* plugin handle */
static hexchat_hook *timerhook = NULL;
static int enable = 1;
static int solver_count = 0;
static char *configdir = NULL;
static char *solver_config = NULL;
static char *watched_channel = NULL;
static char *reply_to = NULL;
static queue_entry *notice_queue = NULL;
static solver_entry solver_list[ MAX_BUF ];
static char fbuf[MAX_BUF];
static char qbuf[MAX_BUF];

static time_t endtime;

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 void
solver_clean(void)
{
	int i;

	if (watched_channel != NULL) {
		free(watched_channel);
		watched_channel = NULL;
	}
	if (reply_to != NULL) {
		free(reply_to);
		reply_to = NULL;
	}
	for ( i = 0; i <= solver_count; i++ ) {
		free(solver_list[ i ].s_trigger);
		free(solver_list[ i ].s_command);
	}
	solver_count = 0;
}

static int
solver_update(void)
{
	FILE *fp;
	char *data;
	char *nl;
	char *cmd;
	int found = 0;

	solver_clean();

	fp = fopen(solver_config, "r");
	if (fp == NULL) {
		hexchat_printf(ph, "solver cant read: %s\n", solver_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] == '!') {
			reply_to = strdup( data + 1 );
			continue;
		}
		cmd = strchr(data, '|');
		if (cmd == NULL)
			continue;
		*(cmd++) = 0;
		if (++found >= MAX_BUF) {
			hexchat_printf(ph, "to many lines\n");
			break;
		}
		while (*data == ' ')
			data ++;
//		hexchat_printf(ph, "solver trigger <%s> action: %s\n", data, cmd);
		solver_list[ solver_count ].s_trigger = strdup( data );
		solver_list[ solver_count ].s_command = strdup( cmd );
		solver_count ++;
	}
	fclose(fp);
	if (watched_channel != NULL)
		hexchat_printf(ph, "Loaded %d triggers for %s\n", found, watched_channel);
	return found;
}

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

	if (endtime > time(NULL))
		return 1; /* return 1 to keep the timeout going */

	/* 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 */
}

#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
solver_parse(char *word[], char *word_eol[], void *userdata)
{
	int i;
	const char *reply;
	const char *line;

	line = word_eol[4] + 1;
	while (*line == ' ')
		line ++;
	for ( i = 0; i < solver_count; i++ ) {
		if (strcasestr(line, solver_list[ i ].s_trigger) != NULL) {
			hexchat_printf(ph, "%s", solver_list[ i ].s_command);
			reply = reply_to;
			if (reply == NULL)
				reply = watched_channel;
			endtime = time(NULL) + 4 + strlen(solver_list[ i ].s_command)/8;
			queue_addf(&notice_queue, "msg %s %s", reply, solver_list[ i ].s_command);
		}
	}
#if 0
	hexchat_printf(ph, "not found %s", line);
#endif
}

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

	if (word[3] == NULL)
		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 */

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

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

	solver_parse(word, word_eol, userdata);
        return HEXCHAT_EAT_NONE; /* don't eat this event, let other plugins and hexchat see it too */
}

static int
solverupdate_cb(char *word[], char *word_eol[], void *userdata)
{
	solver_update();
	return HEXCHAT_EAT_ALL; /* eat this command so hexchat and other plugins can't process 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
solver_toggle_cb(char *word[], char *word_eol[], void *userdata)
{
	if (enable == 0) {
		enable = 1;
		timer_start();
		hexchat_print(ph, "solver now enabled!\n");
		solver_update();
	} else {
		enable = 0;
		queue_delete(&notice_queue);
		timer_end();
		hexchat_print(ph, "solver 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 = "solver";
	*plugin_desc = "solver extensions";
	*plugin_version = "0.3";

	cptr = hexchat_get_info(ph, "xchatdirfs");
	if (cptr == NULL)
		cptr = ".";
	configdir = strdup(cptr);
	snprintf(fbuf, sizeof(fbuf), "%s/solver.config", configdir);
	solver_config = strdup(fbuf);

	hexchat_hook_command(ph, "solver", HEXCHAT_PRI_NORM, solver_toggle_cb,
		"Usage: solver, Turns OFF/ON solver", 0);
	hexchat_hook_command(ph, "solverupdate", HEXCHAT_PRI_NORM, solverupdate_cb,
		"Usage: solverupdate, read config", 0);

	hexchat_hook_server(ph, "PRIVMSG", HEXCHAT_PRI_NORM, privmsg_cb, NULL);

	timerhook = NULL;
	timer_start();

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

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

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

/* EOF */
