#!/usr/bin/perl

use Mail::Internet;
use Net::Jabber qw(Client);
use XML::Simple;
use Getopt::Std;
use File::HomeDir;
use strict;

my (	$server, $port, $Connection, $status, $username, $resource,
		$password, $mail, $to, $from, $body, $subject, $verbose);
our ($opt_v);

getopts('v');
$verbose = $opt_v;

if ($verbose) {
	open (STDOUT, ">>./smtptojabber.log");
	print "-" x 15 . " Connection at " . localtime() . "\n";
}

$mail = Mail::Internet->new(\*STDIN);

chomp ($to      = $mail->get('to'));
chomp ($from    = $mail->get('from'));
chomp ($subject = $mail->get('subject'));
$body = join '', @{$mail->body()};

$to = userpref($to);

# clean up from
$from =~ s/^.*?<(.*?)>.*/$1/;

#my $file = shift || die;
#($username, $password, $server) = readin($file);
($username, $password, $server) = ("smtp", "smtp", "EXAMPLE.com");
($resource = $from) =~ s/@/%/; # change user@domain.com to user%domain.com

$port = 5222;

$Connection = new Net::Jabber::Client();

$Connection->SetCallBacks(
   "message" => \&InMessage,
   "presence" => \&InPresence,
   "iq" => \&InIQ);

$status = $Connection->Connect(
	"hostname" => $server,
	"port" => $port);

my @result = $Connection->AuthSend(
   "username" => $username,
   "password" => $password,
   "resource" => $resource);

$from = convertfrom($from);
if ($verbose) {
	print "Logged in to $server:$port as $username\n";
	print "Trying to send '$subject' to '$to' from '$from'\n";
}

$Connection->MessageSend(
	to       => $to,
	subject  => $subject,
	body     => $body,
	priority =>10);

	#thread	=> $from,
	#thread   => $threadto,

$verbose && print "-" x 15 . " Done!\n";
$verbose && close STDOUT;

sub convertfrom() {
	my $from = shift; # form of 'user@smtp.com'
	$from =~ s/\@/%/; # change to 'user%smtp.com'
	$from .= "\@jsmtp.EXAMPLE.com"; # put the transport and jabber server on there
	return $from;
}

sub readin() {
	my $file = shift;
	my ($xml, $username, $password, $server);
	$xml = XMLin($file);
	$username = $xml->{'username'};
	$password = $xml->{'password'};
	$server   = $xml->{'server'};
	die "Didn't get username or server\n" unless ($username && $server); # password could be null
	return ($username, $password, $server);
}

sub userpref() {
	my $to = shift;
	my $file = home() . "/.jsmtp";
	die "You must have a '$file' file, can't find it\n" unless (-f $file);
	my $xml = XMLin($file);
	my $jid = $xml->{'to'};
	$jid = $ENV{'USER'} unless ($jid);
	$to =~ s/(\@.*)$//;
	foreach my $rules (@{$xml->{'match'}}) {
	   if ($rules->{'email'} eq $to) {
			$jid = $rules->{'jid'};
			last;
		}
	}
	unless ($jid =~ /\@/) {
		my $domain = $xml->{'defaultdomain'};
		if ($domain) {
			$domain = "jsmtp.EXAMPLE.com" unless ($domain =~ /^jsmtp/);
		} else {
			$domain .= "jsmtp.$domain";
		}
		$jid .= "\@$domain";
	}
	$verbose && print "SMTP to '$to' goes to jabber: '$jid'\n";
	return $jid;
}
