#!/usr/bin/perl

$arg = shift;
use File::Basename;

# Append a mime content type tag, and dump the file.
# For html files however, adjust a base tag, if there was none, so
# that possible links may be followed.
# Assumptions: html files have a <html> tag and a <head> ... </head>. The 
# </head> is not on the same line as a <base...> tag.

$viewname = "/view/doc";
$prefix = "/vob";
$mailto = "Marc Girod";
$mailaddr = "girod\@shire.ntc.nokia.com";

# simplify argument: 
#   0) If it starts with $prefix prepend $viewname
#   1) allow access only to $viewname/$prefix subtree
#   2) no .. allowed
#   3) replace // sequences by /
#   4) strip leading and trailing spaces and /'s
$arg =~ s/^($prefix)/$viewname$1/;
if (!($arg =~ /^$viewname$prefix/)) {
  errorpage("Only '$prefix' subtree can be accessed.\n");
}

$arg =~ s/\.\.//g;
while ($arg =~ s/\/\//\//g) {};
$arg =~ /^\s*(.*?)\/?\s*$/;
$arg = $1;
$base = base($arg);

if (!(open(FILE, $arg))) {
  errorpage("Can't open '$arg'.\n");
}

# print out HTML header
print "Content-type: text/html\n\n";
while ((defined ($line = <FILE>)) && ($line !~ /<html>/i)) {
    print $line;
}
if ($line =~ /<html>/i) {
    my $btag = 0;
    print $line;
    until (($line = <FILE>) =~ /<\/head>/i) {
	if ($line =~ /<base.*?>/) {
	    $btag = 1;
	} elsif ($line =~ /<link rel=\"stylesheet\".*?>/i) {
	    $line = hacklink($line);
	}
	print $line;
    }
    if (!$btag) {
	print "<base href=\"$base\">\n";
	print $line;
    }
}
print <FILE>;
close(FILE);
exit(0);

sub errorpage {
  my $msg = shift;

  # print out HTML header
  print <<HTML;
Content-type: text/html

<html>
<head><title>Error</title></head>
<body><hr><h1>Error:</h1>
<h3>$msg</h3>
<hr>
<address>
This page is automagically generated.
Mail your remarks to <a href="mailto:$mailaddr">$mailto</a>
</address>
</body>
</html>
HTML

  exit(0);
}

sub base($) {
    my $arg = shift;
    $arg =~ s/^([^@]*)@@.*/$1/;
    my $dir = dirname("$arg");

    if ($dir =~ /$viewname(.*)/) {
	$dir = $1;
    }
    return "http://$ENV{SERVER_NAME}:$ENV{SERVER_PORT}$dir/";
}

# Hack around a Netscape bug
sub hacklink($) {
    my $line = shift;
    $line =~ /^(.*href=\"?)([^\" ]*?)([\" ].*)/i;
    my ($fst, $snd, $thd) = ($1, $2, $3);
    unless ($snd =~ /:/) {
	$snd = norm($base, $snd);
    }
    return "${fst}${snd}${thd}\n";
}

sub norm($$) {
    my @fst = split(/\//, shift);
    my @snd = reverse split(/\//, shift);
    while ($snd[$#snd] eq "..") {
	$#fst--;
	$#snd--;
    }
    return join("/", @fst) . "/" . join("/", reverse @snd);
}
