#!/usr/bin/perl
# sburke@cpan.org Time-stamp: "2006-09-01 20:51:31 ADT"
# desc{ makes calls to 'mail' invoke Thunderbird  }
#---------------------------------------------------------------------------
#
# This 'mail' program traps old-timey calls to 'mail' (to start a new mail
#  message) and invokes Thunderbird ( http://www.mozilla.com/thunderbird/ )
#
# Only the -s (Subject) and -c (carboncopy) switches are supported.
#
# And you can't (yet?) use address book nicknames or local names as
#  destination addresses -- you have to use full addresses.
#
# Examples:
#   mail -s Bored freundleiven@example.com
#   mail -s "Let's get crazy drunk" stuff@there.mil 
#   mail jojo@crunk.int
#   mail jojo@crunk.int whoever@stuff.gov
#   cal | mail -s Now me@job.com
#     (when STDIN isn't a terminal, we copy it to the message body)
#
use strict;
use warnings;
use Getopt::Std;
use URI::Escape;

getopt("cs", \my %o);
my @to = grep length($_), @ARGV;
die "Who to mail?" unless @to;
my @cc = grep length($_), split ',', $o{'c'} || '';    

my @baddies =
  grep  # but cf perlfaq9
    !m/\A [^\@+]+ \@ ( [^\.]+ \. )+ [^\.]+ \z/x
    => @to, @cc;
#@baddies and die "Invalid addresses: @baddies\n";

my $body = -t *STDIN ? '' : join '', <STDIN>;

sub u { join "," => map uri_escape($_), @_; }

my @params = (
 @cc     ? (     "cc=" . u @cc    ) : (),
 $o{'s'} ? ("subject=" . u $o{'s'}) : (),
 $body   ? (   "body=" . u $body  ) : (),
);

my $url =  join('',
 'mailto:',
 u(@to),
 @params ? ("?" . join "&", @params) : (),
);

print "=> $url\n" if length($url) < 200;
exec 'mozilla-thunderbird', '-compose', $url;
die "Couldn't exec?! $!";
 # http://kb.mozillazine.org/Command_line_arguments_%28Thunderbird%29#Issues
 # notably: somebody@somewhere?cc=address@provider&subject=hi&body=something
