#!C:\Perl\Bin\Perl -W
#!/usr/bin/perl

# ---------------------------------------------------------------------
# Coded by Andrea Setti 17-03-2005 - Reggio Emilia - ITALY
# infos to: my $domain ='eone group';
#				   $domain =~ s/\ //;
#				print "asetti at " . $domain . " dot it";
# released under the GNU Public License
# see http://www.gnu.org/copyleft/gpl.html for further infos.
# ---------------------------------------------------------------------

# ---------------------------------------------------------------------
# ToDo: 1. forward $objHTMessage to the real browser
#       2. handle POST information about login and password
#          (see line 13 to 17 of this script)
#       3. change the references to the real ones on $objHTMessage 
#          (they could point to the mechanize object that are links 
#          to the server's cache.
# ---------------------------------------------------------------------

use strict;
use Net::SSLeay;
use WWW::Mechanize;
use LWP::UserAgent;
use HTTP::Cookies;
use HTTP::Headers;
use HTTP::Message;
#use CGI;

# these variables will be passed by a CMS webpage via POST
# passing these variables has to be implemented.
my $login_url = 'http://<mysite>/<mycgi-dir>/<mycgiscript>';
my $username  = 'my_login_username';
my $password  = 'my_login_password';

# initializes cookies and fetches the login page
my $mech = WWW::Mechanize->new(cookie_jar => {});
$mech->agent_alias( 'Windows IE 6' );
$mech->get($login_url);

# check result
$mech->success or die "Can't get the search page";

# fills the login page and saves all the form input_values
$mech->submit_form(
    form_name => 'a',
    fields => {
        wtusername => $username,
        wtpassword => $password,
        },
    );

# to fetch also the cookies, i need to build a new HTTP message, 
# using HTTP::Message i can attach both the cookies fetched by the login page and the content of the authenticated page.
#my $redirect_url = ${$mech->{req}->{_uri}}."?".$mech->{req}->{_content};
my $headers       = HTTP::Headers->new;
   $headers       = $mech->{req}->{_headers};
my $html_response = $mech->{content};

# builds the HTTP::Message object
my $objHTMessage  = HTTP::Message->new($headers,$html_response);

#print $redirect_url."\n\n".$headers->as_string."\n\n";
#my $objCGI = new CGI;

# prints out the object
print $objHTMessage->as_string;
