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

 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.

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

	downloader - a plugin for xchat2
	================================

	$Id: downloader.c,v 1.17 2006/02/20 18:06:28 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 <time.h>

#include <fcntl.h>


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
#define	XDCC_TIMEOUT	180


typedef struct _queue_entry {
	struct _queue_entry *q_next;
	xchat_context *q_context;
	char *q_data;
	char *q_nick;
} queue_entry;


static xchat_plugin *ph; /* plugin handle */
static xchat_hook *timerhook = NULL;
static int enable = 1;
static volatile int get_downloads_active = 0;
static queue_entry *download_queue = NULL;
static char *fixed_channel = NULL;
static char *download_current = NULL;
static time_t download_started = 0;
// 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, const char *nick)
{
	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_context = xchat_get_context(ph);
	new->q_data = (data != NULL) ? strdup(data) : NULL;
	new->q_nick = (nick != NULL) ? strdup(nick) : NULL;
	return new;
}

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

	if (queue == NULL)
		return;

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

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

	if (queue == NULL)
		return NULL;

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

	*queue = old->q_next;
	return old;
}

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);
		if (old->q_nick != NULL)
			free(old->q_nick);
		*queue = old->q_next;
		free(old);
		old = *queue;
	}
	return;
}

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

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

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

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

	if (queue == NULL)
		return;

	old = *queue;
	while (old != NULL) {
		if (old->q_data != NULL)
			xchat_printf(ph, "%s\n", old->q_data);

		old = old->q_next;
	}
	return;
}

static void
get_next_file(void)
{
	xchat_context *backup;
	xchat_context *action;
	queue_entry *qe;

	if (download_current != NULL) {
		free(download_current);
		download_current = NULL;
	}

	qe = queue_get(&download_queue);
	if (qe != NULL) {
		backup = xchat_get_context(ph);
		if (fixed_channel != NULL) {
			action = xchat_find_context(ph, NULL, fixed_channel);
		} else {
			action = xchat_find_context(ph, NULL, qe->q_nick);
			if (action != NULL)
				xchat_set_context(ph, action);
			action = qe->q_context;
		}
		if (action != NULL)
			xchat_set_context(ph, action);
		xchat_command(ph, qe->q_data);
		download_current = qe->q_data;
		download_started = time(NULL);
		xchat_set_context(ph, backup);
		free(qe->q_nick);
		free(qe);
	}
}

static void
get_downloads(void)
{
	xchat_list *list;
	int s;
	int t;
	int d;

	list = xchat_list_get(ph, "dcc");
	if (list == NULL)
		return;

	d = 0;
	while (xchat_list_next(ph, list))
	{
		t = xchat_list_int(ph, list, "type");
		if (t != 1) /* DCC Type: 1-Receive */
			continue;
		s = xchat_list_int(ph, list, "status");
		if (s != 1) /* DCC Status: 1-Active */
			continue;
		d ++;
	}
	xchat_list_free(ph, list);
	if (d > 0)
		return;
	get_next_file();
}

static void
check_downloads(void)
{
	time_t save;

	save = download_started + XDCC_TIMEOUT;
	if (time(NULL) < save)
		return;

	/* avoid parallelel start */
	if (get_downloads_active++ > 0)
		return;

	get_downloads();
	get_downloads_active = 0;
}

static int timeout_cb(void *userdata)
{
	check_downloads();
	return 1; /* return 1 to keep the timeout going */
}

#if 0
        word    text

        1       :XDCC|dinoex!~dinoex@euirc-c679c75c.dinoex.sub.de
        2       PRIVMSG
        3       dinoex
        4       :**
        5       Transfer
        6       Completed
#endif

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

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

	check_downloads();
	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)
{
	if (enable == 0)
		return XCHAT_EAT_NONE; /* don't eat this event, let other plugins and xchat see it too */

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

	check_downloads();
	return XCHAT_EAT_NONE; /* don't eat this event, let other plugins and xchat see it too */
}

static int
xdccget_cb(char *word[], char *word_eol[], void *userdata)
{
	long i;
	long von;
	long bis;

	if (word_eol[2] == NULL)
		return XCHAT_EAT_ALL;
	if (word_eol[3] == NULL)
		return XCHAT_EAT_ALL;
	queue_addf(&download_queue, word[2], "msg %s xdcc get %s", word[2], word[3]);
	xchat_printf(ph, "xdccget %s %s\n", word[2], word[3]);
	if (word_eol[4] == NULL)
		return XCHAT_EAT_ALL;
	von = atol(word_eol[3]) + 1;
	bis = atol(word_eol[4]);
	for (i=von; i<=bis; i++) {
		queue_addf(&download_queue, word[2], "msg %s xdcc get %ld", word[2], i);
		xchat_printf(ph, "xdccget %s %ld\n", word[2], i);
	}
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

static int
xdq_cb(char *word[], char *word_eol[], void *userdata)
{
	xchat_print(ph, "xdcc download queue:\n");
	queue_list(&download_queue);
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

static int
xdccnext_cb(char *word[], char *word_eol[], void *userdata)
{
	get_next_file();
	return XCHAT_EAT_ALL; /* eat this command so xchat and other plugins can't process it */
}

static int
xdlock_cb(char *word[], char *word_eol[], void *userdata)
{
	if (fixed_channel != NULL)
		free(fixed_channel);

	if (word[2] == NULL)
		return XCHAT_EAT_ALL;

	fixed_channel = strdup(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
downloader_toggle_cb(char *word[], char *word_eol[], void *userdata)
{
	if (enable == 0) {
		enable = 1;
		get_downloads_active = 0;
		timer_start();
		xchat_print(ph, "downloader now enabled!\n");
		download_started = time(NULL);
	} else {
		enable = 0;
		get_downloads_active = 1;
		timer_end();
		if (download_current != NULL) {
			free(download_current);
			download_current = NULL;
		}
		queue_delete(&download_queue);
		xchat_print(ph, "downloader 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)
{
	/* we need to save this for use with any xchat_* functions */
	ph = plugin_handle;

	*plugin_name = "downloader";
	*plugin_desc = "xdcc download bot";
	*plugin_version = "0.7";

	timerhook = NULL;
	timer_start();

	xchat_hook_command(ph, "downloader", XCHAT_PRI_NORM, downloader_toggle_cb,
		"Usage: downloader, Turns OFF/ON file server", 0);
	xchat_hook_command(ph, "xdccget", XCHAT_PRI_NORM, xdccget_cb,
		"Usage: xdccget nick pack [end], add a pack to the wanted files", 0);
	xchat_hook_command(ph, "xdq", XCHAT_PRI_NORM, xdq_cb,
		"Usage: xdq, show current download queue", 0);
	xchat_hook_command(ph, "xdccnext", XCHAT_PRI_NORM, xdccnext_cb,
		"Usage: xdccnext, start next download", 0);
	xchat_hook_command(ph, "xdlock", XCHAT_PRI_NORM, xdlock_cb,
		"Usage: xdlock channel,  lock download to channel", 0);

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

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

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

void
xchat_plugin_deinit(void)
{
	if (download_current != NULL) {
		free(download_current);
		download_current = NULL;
	}

	queue_delete(&download_queue);
}

/* EOF */
