/* Copyright (C) 2006 Damir Bikmuhametov */

/* Installation:
 
1. Install and configure Whoson.

2. export dovecot=/psth/to/dovecot/sources

   gcc -Wall -W -shared -fPIC -DHAVE_CONFIG_H -I$dovecot -I$dovecot/src/lib \
   -I/usr/local/include -L/usr/local/lib whoson.c -o whoson.so -lwhoson

   cp whoson.so /usr/local/lib/dovecot/imap/
   cp whoson.so /usr/local/lib/dovecot/pop3/

3. Read http://wiki.dovecot.org/PopBSMTPAndDovecot and configure Dovecot
   properly. Use 'DRAC' section of the Wiki as the template.

4. Upon (re-)starting Dovecot you will get an error message:
   "WHOSON: IP environment not given". Do not worry, it's pretty normal.
*/

#include "lib.h"
#include "ioloop.h"
#include "network.h"

#include <stdlib.h>
#include <string.h>
#include <whoson.h>

#define WHOSON_TIMEOUT_SECS 60
#define IPADDR_LEN 16
#define USERNAME_LEN 100

static struct timeout *to_whoson = NULL;
static struct ip_addr ip;

static char ipaddr[IPADDR_LEN];
static char user[USERNAME_LEN];

static void whoson_timeout(void *context __attr_unused__)
{
	if (wso_login(ipaddr, user, NULL, 0) == -1)
		i_error("wso_login() failed");
}

void whoson_init(void)
{
	const char *ip_str;
	const char *user_env;

	ip_str = getenv("IP");
	user_env = getenv("USER");

	if (ip_str == NULL || *ip_str == '\0')
		i_error("WHOSON: IP environment not given");
	else if (net_addr2ip(ip_str, &ip) < 0)
		i_error("WHOSON: net_ip2addr(%s) failed: %m", ip_str);
	else if (!IPADDR_IS_V4(&ip))
		i_error("WHOSON: Only IPv4 addresses are supported (%s)", ip_str);
	else {
		if (user_env == NULL || *user_env == '\0')
			user_env = "dovecot";

		(void)strlcpy(ipaddr, net_ip2addr(&ip), IPADDR_LEN);
		(void)strlcpy(user, user_env, USERNAME_LEN);

		whoson_timeout(NULL);
		to_whoson = timeout_add(1000*WHOSON_TIMEOUT_SECS,
				      whoson_timeout, NULL);
	}
}

void whoson_deinit(void)
{
	if (to_whoson != NULL)
		timeout_remove(&to_whoson);
}
