#!/usr/bin/perl

use warnings;
use strict;

use AnyEvent::SMTP::Server;
use Data::Dump qw(dump);

use lib 'lib';
use MQR::Redis;

my $host = $ENV{SMTP_HOST} || '0.0.0.0';
my $port = $ENV{SMTP_PORT} || 2525;

my $server = AnyEvent::SMTP::Server->new( host => $host, port => $port );

$server->reg_cb(
	client => sub {
		my ($s,$con) = @_;
		warn "Client from $con->{host}:$con->{port} connected\n";
	},
	disconnect => sub {
		my ($s,$con) = @_;
		warn "Client from $con->{host}:$con->{port} gone\n";
	},
	mail => sub {
		my ($s,$mail) = @_;
		my $from = $mail->{from};
		warn "Received mail from $from to ",join(' and ',@{$mail->{to}}), "\n$mail->{data}\n";
		foreach my $to ( @{ $mail->{to} } ) {
			my $subject = $1 if $mail->{data} =~ m/^Subject:\s*(.+)$/m;
			$subject =~ s/[\s\r\n]+$//; # XXX important!
			MQR::Redis->publish( "MSG $host:$port smtp $mail->{from} $to" => $subject );
		}
	},
);

$server->start;
AnyEvent->condvar->recv;
