#!/usr/local/bin/perl 

use lib "/etc/lighttpd/lib/perl/";
use strict; 
use HTML::Mason::CGIHandler; 
use CGI::Fast; 
use CGI::Carp;
use Data::Dumper;

{
 package HTML::Mason::Commands;
 	use Data::Dumper;
 	use CGI;
	use CGI::Carp;

	use vars qw/%globals %lits $conn/;
	}

my $cgi;
my %h;

while ($cgi = new CGI::Fast) {
	my @comp_roots;
	umask 002;

	# We could do this instead of the virtual hosting
	# my ($comp_root) = $ENV{DOCUMENT_ROOT} . $ENV{HTTP_HOST};
	# But instead we serveralias and just live with the root
	my ($comp_root) = $ENV{DOCUMENT_ROOT};

	my $data_root = "/etc/lighttpd/HTML-Mason/data/";
	if ($comp_root =~ m#([^/]+)/?$#){
		$data_root .= $1;
		}

	my $uri = $ENV{REQUEST_URI};
	if ($uri =~ /^([^\?]*)(?:\?(.*))?/){
		$ENV{PATH_INFO} = $1;
		}
	# warn Dumper(\%ENV);

	# FakeApache will put SCRIPT_NAME and PATH_INFO together for uri
	$ENV{SCRIPT_NAME} = '';

	$ENV{PATH_INFO} .= 'index.html' if ($ENV{PATH_INFO} =~ m#/$#);

	# warn "\nComp root: $comp_root\nPath: $ENV{PATH_INFO}";

	unshift @comp_roots, ['web' => $comp_root];

	if (! $h{$comp_root}){
		$h{$comp_root} = HTML::Mason::CGIHandler->new(
			comp_root	=> \@comp_roots,
			data_dir 	=> $data_root,
			error_format => 'html',
			);
		}

	%HTML::Mason::Commands::globals = ();
	$cgi->charset('');

	eval { $h{$comp_root}->handle_cgi_object($cgi) };
	if (my $raw_error = $@) {
		# print out a pretty system error page and log $raw_error
		print $raw_error;
		exit;
		}
	}

exit 0;

