package PLP::CGI;

use strict;

our $VERSION = '1.01';

use PLP;

# CGI initializer: opens SCRIPT_FILENAME
sub init {
	$PLP::print = 'print';

	if (defined $ENV{PATH_TRANSLATED}) {
		# Physical mapping provided; SCRIPT_* points to handler script
		# (Apache action)
		my $path = delete $ENV{PATH_TRANSLATED};
		my $path_info;
		while (not -f $path) {
			if (not $path =~ s/(\/+[^\/]*)$//) {
				printf STDERR "PLP: Not found: $path$path_info ($ENV{REQUEST_URI})\n";
				PLP::error(undef, 404);
				exit;
			}
			# move last path element from PLP_*NAME to PATH_INFO
			$path_info = $1 . $path_info;
		}
		$ENV{PLP_FILENAME} = $path;
		$ENV{PLP_NAME} = delete $ENV{PATH_INFO};
		if (defined $path_info) {
			$ENV{PLP_NAME} =~ s/\Q$path_info\E$//;
			$ENV{PATH_INFO} = $path_info;
		}
	} else {
		# SCRIPT_*/PATH_INFO already modified to target script
		# (Lighttpd cgi.assign)
		$ENV{PLP_FILENAME} = $ENV{SCRIPT_FILENAME};
		$ENV{PLP_NAME} = $ENV{SCRIPT_NAME};
	}

	if (not -r $ENV{PLP_FILENAME}) {
		print STDERR "PLP: Can't read: $ENV{PLP_FILENAME} ($ENV{REQUEST_URI})\n";
		PLP::error(undef, 403);
		exit;
	}

	delete @ENV{
		qw(SCRIPT_NAME SCRIPT_FILENAME),
		grep /^REDIRECT_/, keys %ENV
	};

	my ($file, $dir) = File::Basename::fileparse($ENV{PLP_FILENAME});
	chdir $dir;

	$PLP::code = PLP::source($file, 0, undef, $ENV{PLP_FILENAME});
}

# This is run by the CGI script. (#!perl \n use PLP::CGI; PLP::CGI::everything;)
sub everything {
	PLP::clean();
	init();
	PLP::start();
}

1;

