#!/usr/bin/perl
#

#use FCGI;
use Data::Dumper;
use lib "/opt/snt-fancyindex/lib/";
use SNT::FancyIndex;
use File::stat;			# We need 'stat' info on files/directories


use CGI::Fast qw(:standard);
while (new CGI::Fast) {

#while (FCGI::accept() >= 0)
#{
	my $uri = $ENV{'REQUEST_URI'};
	my $docroot = $ENV{'DOCUMENT_ROOT'};

	my $motd = 'default';
	if(defined $ENV{'MOTD'})
	{
		$motd = $ENV{'MOTD'};
	} else {
		# alternative docroots
		$motd = 'debian' if $docroot eq '/space/debian/';
		$motd = 'maarten' if $docroot eq '/maarten/';
	}


	if($motd eq 'default')
	{
		$uri =~ s|^/debian|/pub/os/linux/debian|;
		
	}
	my $path = $docroot . $uri;


	## check if the path exists, and if so, if its a dir
	my $inode = stat($path);
	if (!defined $inode)
	{
		# it does not exists
		# GO away
		#print "Status: 404 Not Found\n";
		print "\n";
		print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
		<html><head>
		<title>404 Not Found</title>
		</head><body>
		<h1>Not Found</h1>
		<p>The requested URL '.$ENV{'REQUEST_URI'}.' was not found on this server.</p>
		#<hr><pre>';
		#print Dumper(%ENV);
		#print '</pre>';
		print '</body></html>';
		print "\n";

		next;
	} else  {
		## is't a dir, index it
		my $templatedir = $ENV{'OURTEMPLATES'};
		my $skin = "";

#		print "HTTP/1.0 200 OK\n";
		#set last modified
		print "Last-Modified: ".  HTTP::Date::time2str($inode->mtime)."\n";

		# cache this
		print "Expires: ".HTTP::Date::time2str(time+60)."\n";

		## we are going to do the output
		print "Content-Type: text/html\n";
		print "\n";

		## give it to my  baby
		# my $path = $r->filename;
		# my $uri = $r->uri();
		SNT::FancyIndex::index($path,$ENV{'REQUEST_URI'},$skin,$motd,$templatedir);
		print '<!-- '.$motd.'-'.$docroot.'-'.$ENV{SCRIPT_NAME}.'-->';

	}
}


