#!perl
# -*- Perl -*-
# Copyright 1999 Greg Spencer (greg_spencer@acm.org)

######################################################################
#
# Argument parsing
#
######################################################################

use p4Config;
use p4Util;
use CGI;
use LWP::MediaTypes;
use HTTP::Date;

sub GetModDate {
    my $file = shift;
    my %filehash = &p4Util::GetFileInfo($file);
    my $modtime = $filehash{$file}{headTime};
    my $date = &time2str($modtime);

    return $date;
}

$query = new CGI;
$input_file=$query->path_info();

# it's been given as a script argument via the url...
if (!$input_file) {
	@param_keys = $query->keywords;
	$input_file=$param_keys[0] if !$input_file;
}

$input_file =~ s,^//depot,,; # make sure it isn't already there.
$input_file = "//depot".$input_file; # so we don't have to give the depot...

$input_file =~ s|/$||; # strip a trailing slash...
($file_name = $input_file) =~ s/\[#\@].*$//; # strip off the version number, if any

$type = guess_media_type($file_name);

$type = "text/plain" if ($type eq "application/octet-stream");

if (!open(INPUT,"p4 print \"$input_file\" 2>&1 |")) {
    print "Status: 200 OK\n";
    print "Content-type: text/html\n\n";
    print "<HTML><TITLE>Unable to open file...</TITLE><BODY bgcolor=white>\n";
    print "<H2>$input_file</H2><HR>\n";
    print "<BR><CENTER><B><FONT color=red size=+2>\n";
    print "Unable to run Perforce on server (this shouldn't happen!)\n";
    print "</FONT></B></CENTER><BR>\n";
    print "<HR></BODY></HEAD>\n";
    exit(0);
}

my $info = <INPUT>; # strip off the perforce info...
if ($info =~ m/(no such file|protected namespace)/) {
    print "Status: 200 OK\n";
    print "Content-type: text/html\n\n";
    print "<HTML><TITLE>Unable to open file...</TITLE><BODY bgcolor=white>\n";
    print "<H2>$input_file</H2><HR>\n";
    print "<BR><CENTER><B><FONT color=red size=+2>\n";
    
    if ($version) {
	print "There is no such revision number...";
    }
    elsif ($changenum) {
	print "There is no such change number...";
    }
    else {
	print "File or Path Doesn't Exist.\n";
    }
    print "</FONT></B></CENTER><BR>\n";
    print "<HR></BODY></HEAD>\n";
    
    exit(0);
}

$modDate = &GetModDate($input_file);
print "Status: 200 OK\n";
print "Content-type: $type\n";
if ($modDate ne "") {
    print "Last-modified: $modDate\n";
}
print "\n";

# keep from loading these files into memory 
# (as they might be BIG binary files)
while (<INPUT>) { print; }