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

 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.

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

	ahop - a plugin for xchat2
	==========================

	$Id: ahop.c,v 1.9 2006/07/25 09:34:05 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 <ctype.h>

#include <fcntl.h>
#ifdef linux
#include <sys/file.h>
#include <db_185.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 *options_db = NULL;
static const char *watched_channel = "#anime-fansubs";
static time_t next_action = 0;
static queue_entry *notice_queue = NULL;
static char *update_job = NULL;
static char *update_work = NULL;
static char *update_done = NULL;
static char fbuf[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 *
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
ahop_check(void)
{
	FILE *flog;
	FILE *fp;
	char *data;
	char *nl;
	int rc;

	fp = fopen(update_job, "r");
	if (fp == NULL)
		return;

	fclose(fp);
	rc = rename(update_job,update_work);
	if ( rc != 0 ) {
		xchat_printf(ph, "ahop cant rename: %s -> %s: %d\n", update_job, update_work, rc);
		return;
	}
	flog = fopen(update_done, "a");
	if (flog == NULL) {
		xchat_printf(ph, "ahop cant write: %s\n", update_done);
		return;
	}
	fp = fopen(update_work, "r");
	if (fp == NULL) {
		xchat_printf(ph, "ahop cant read: %s\n", update_job);
		fclose(flog);
		return;
	}
	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;
		xchat_printf(ph, "ahop action: %s\n", data);
		fputs(data, flog);
		fputs("\n", flog);
		queue_add(&notice_queue, data);
	}
	fclose(fp);
	unlink(update_work);
	fclose(flog);
	return;
}

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

	/* process queued buffer */
	if (notice_queue != NULL) {
		backup = xchat_get_context(ph);
		watch = xchat_find_context(ph, NULL, watched_channel);
		if (watch != NULL) {
			data = queue_get(&notice_queue);
			if (data != NULL) {
				xchat_set_context(ph, watch);
				xchat_command(ph, data);
				free(data);
			};
		};
		xchat_set_context(ph, backup);
	};

	if (next_action == 0)
		return 1;

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

	next_action = time(NULL) + 30;

	backup = xchat_get_context(ph);
	watch = xchat_find_context(ph, NULL, watched_channel);
	if (watch != NULL) {
		ahop_check();
	};
	xchat_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 int
ahopdo_cb(char *word[], char *word_eol[], void *userdata)
{
	xchat_context *backup;
	xchat_context *watch;

	backup = xchat_get_context(ph);
	watch = xchat_find_context(ph, NULL, watched_channel);
	if (watch != NULL) {
		ahop_check();
	};
	xchat_set_context(ph, backup);
	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
ahop_toggle_cb(char *word[], char *word_eol[], void *userdata)
{
	if (enable == 0) {
		enable = 1;
		timer_start();
		xchat_print(ph, "ahop now enabled!\n");
	} else {
		enable = 0;
		queue_delete(&notice_queue);
		timer_end();
		xchat_print(ph, "ahop 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;
	const char *chan;

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

	*plugin_name = "ahop";
	*plugin_desc = "auto hop bot";
	*plugin_version = "0.3";

	cptr = xchat_get_info(ph, "xchatdirfs");
	if (cptr == NULL)
		cptr = ".";
	configdir = strdup(cptr);
	snprintf(fbuf, sizeof(fbuf), "%s/aoptions.db", configdir);
	options_db = strdup(fbuf);
	snprintf(fbuf, sizeof(fbuf), "%s/job", configdir);
	update_job = strdup(fbuf);
	snprintf(fbuf, sizeof(fbuf), "%s/job.work", configdir);
	update_work = strdup(fbuf);
	snprintf(fbuf, sizeof(fbuf), "%s/job.done", configdir);
	update_done = strdup(fbuf);

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

	xchat_hook_command(ph, "ahop", XCHAT_PRI_NORM, ahop_toggle_cb,
		"Usage: ahop, Turns OFF/ON ahop", 0);
	xchat_hook_command(ph, "ahopdo", XCHAT_PRI_NORM, ahopdo_cb,
		"Usage: ahopdo, run actions", 0);

	next_action = time(NULL) + 2;

	timerhook = NULL;
	timer_start();

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

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

void
xchat_plugin_deinit(void)
{
	queue_delete(&notice_queue);
	if (configdir != NULL)
		free(configdir);
	if (options_db != NULL)
		free(options_db);
	if (update_job != NULL)
		free(update_job);
	if (update_work != NULL)
		free(update_work);
	if (update_done != NULL)
		free(update_done);
}

/* EOF */
