#!/usr/bin/perl
use strict;
use Getopt::Std;
use HTTP::Request::Common;
use LWP::UserAgent;
use MIME::Lite;
use vars qw(%opt);

=head1 NAME

	sendpage.pl

=head1 SYNOPSIS
 
	sendpage.pl [-f from -c cc -s subject -b href ] url1 [url2 ...]
                                                                          
=head1 DESCRIPTION
 
	This utility fetches a web page and sends it to the specified recipient
	as an attached HTML page.
 
	Options:
 
		-t To email address (recipient).
		-f From email address (sender).
		-c CC email address (quote if it's a list).
		-s subject line (quote it).
		-b base href

		url is of course, a web address. 

=head1 EXAMPLES

	perl sendpage.pl -t mary@seds.org -f smiley@seds.org -s "Pets Of the Day!"
	http://catoftheday.com http://dogoftheday.com http://petoftheday.com

=cut
 
### fetch the command line parameters
        getopts('t:f:c:s:b:', \%opt);

	die "Usage: sendpage.pl -t to [-f from -c cc -s subject -b href] url1 [url2 ...]\n"
	 unless($opt{t} ne "" &&  $#ARGV>=0);

### Create a new multipart message:
	my $msg = MIME::Lite->new(
		From    => $opt{f},
        	To      => $opt{t},
        	Cc      => $opt{c},
        	Subject => $opt{s},
        	Type    =>'multipart/mixed'
        );


### Create a new LWP useragent
	my $ua=LWP::UserAgent->new();

# attach the fetched urls
for my $url (@ARGV) {
	my $res=$ua->request(GET $url);
	my $html=$res->content;

	if($opt{b}) {
		my $href=$opt{b};
		$href.='/' unless($href=~/\/$/);
		my $base="<base href=\"$href\">";
		$html =~ s/<\/head>/$base<\/head>/i;
		}
	elsif ($html !~ /<base/i) {
		my $href=$url;
		$href=~s/\/*\w+\.\w+$/\//;
		$href.='/' unless($href=~/\/$/);
		my $base="<base href=\"$href\">";
		$html =~ s/<\/head>/$base<\/head>/i;
		}

	### Add parts (each "attach" has same arguments as "new"):
	$msg->attach(
		Type     => 'text/html',
	        Data     => $html
        ) if($res->is_success);
}
 
### Send in the "best" way (the default is to use "sendmail"):
$msg->send;