#!/usr/bin/perl
##############################################################################################################
# DirectorySlashHack						Version 1				     
# Matthew Gillespie						braindeadprojects@pa.net			     
# 10/25/2009												     
##############################################################################################################
# There's downsides to the Apache provided DirectorySlash config option.
# When set to "on", httpd checks to determine if the resource (not ending in a slash)
# is a file or a directory. If a directory, httpd issues a 301 redirect, forcing the browser
# to re-request a correctly identified resource. (directory/) This allows DirectoryIndexes to be searched,
# and if none are found, either the directory contents are displayed (if +Indexes is set) or
# send back a 400-level forbidden message.
#
# This works really well, _except_ in the instance of a proxy being in use. The proxy (used to mask
# the true hostname) pulls the resource and displays it as it's own. Only the 301 is passed back to the
# browser with the proxied-to hostname in the Location header. This kills the transparency, and there doesn't 
# appear to be any configurable options for DirectorySlash.
##############################################################################################################

use warnings;
use strict;


$|=1;

#Signal Handlers
$SIG{TERM} = \&directoryslashhack_shutdown;
$SIG{INT} = \&directoryslashhack_shutdown;


my $DEBUG=0;
my $proxy_host="www.proxy.net";
my $basedir="/home/sites/user.proxiedto.net";


while (defined(my $input = <STDIN>)) {

	if ($DEBUG) { open(LOGFILE,">>/tmp/testlog.log"); }

	chomp $input;


	$input=~m/^(.*)\*(.*)\*(.*)/;

	my $crap=$1;
	my $username=$2;
	my $path=$3;

	$username=~m/^(.)(.)/;
	my $firstletter=$1;
	my $secondletter=$2;



	my $cleandir="$basedir/$firstletter/$secondletter/$username/www$path";	
	my $response="NULL";

	if ($path=~m/\/$/)
	{
		$response="$cleandir\n";
		if ($DEBUG) { print LOGFILE "0 - $input | $response";	}	
	}

	elsif ($path eq "")
	{
		$response="http://$proxy_host/~$username/\n";
		if ($DEBUG) { print LOGFILE "1 - $input | $response"; }		
	}

	elsif ( -d $cleandir)
	{
		$response="http://$proxy_host/~$username/$path/\n";
		if ($DEBUG) { print LOGFILE "2 - $input | $response"; }
	}
	else
	{
		$response="$cleandir\n";
		print LOGFILE "3 - $input | $response";
	}	

	print $response;

	close LOGFILE;
}
exit(0);

sub directoryslashhack_shutdown($)
{
 exit(0);
}
