#!/usr/bin/perl

############################################################################
#
# NAME: CVSVIEW
# AUTHOR: maarten.deboer@iua.upf.es
# LICENSE: GNU GPL
#
############################################################################
#
# INSTRUCTIONS:
# Create  a user cvsview. The script is executed through inetd, with this 
# user:
#
# From /etc/inetd.conf:
# cvsview	stream	tcp	nowait	cvsview	/usr/sbin/tcpd	/usr/bin/cvsview
# 
# From /etc/services:
# cvsview		XXXX/tcp			# cvsview
#
# where XXXX is the port you want to use. You can perfectly use 80, but
# make sure you don't have another webserver running on that port already
# 
# The users homedir /home/cvsview is were the working copies are stored.
# It has the following permissions:
# drwxr-s---    6 cvsview  cvsview      4096 Mar  7 17:33 /home/cvsview/
# 
# You can control which CVS directories can be accessed by the user cvsview
# with standard permissions.
#
###########################################################################

$|=1;

$path = <STDIN>;
$path =~ m/^GET \/([^ ]+)/;
$path = $1;

# When a directory is requested, we check for a index.htm/index.html file,
# and display that, or we show the directory listing.
if ( -d "/mnt/cvsroot/$path" )
{
	$path =~ s/\/$//;
	if ( -f "/mnt/cvsroot/$path/index.htm,v")
	{
		$path="$path/index.htm";
	}elsif ( -f "/mnt/cvsroot/$path/index.html,v")
	{
		$path="$path/index.html";
	}else{
		@entries = split "\n",`cd /mnt/cvsroot/$path ; ls *,v 2> /dev/null`;
		print<<END;
HTTP/1.1 200 OK
Content-Type: text/html

<HTML>
<HEAD><TITLE>CVSVIEW: $path</TITLE>
<BODY BGCOLOR=white>
<FONT FACE=Courier SIZE=4>
END
		foreach $entry (@entries)
		{
			$entry =~ s/,v$//;
			print "<A HREF=/$path/$entry>$entry</A><BR>\n";
		}
		print "</FONT></HTML></BODY>";
		exit(0);
	}
}

# Check out the requested file. The working copy is in /home/cvsview
$err=`cd /home/cvsview ; /usr/bin/cvs -d /mnt/cvsroot checkout $path 2>&1`;
if ($err)
{
	if ($err=~m/^U /)
	{
		
	}
	else
	{
		print "<H1>Error</H1>$err";
		exit(0);
	}
}
$path=~m/\.(\w+)$/g;
$extIN=$1;
# check the mimetype of the requested file
open(INFILE,"/etc/mime.types");
while (<INFILE>)
{
	chop();
	($mimetype,@extensions)=split " ";
	foreach $ext (@extensions)
	{
		if (lc($ext) eq lc($extIN))
		{
			goto cont;
		}
	}	
}
$mimetype="";
cont:
close(INFILE);
print "HTTP/1.1 200 OK\n";
print "Content-Type: $mimetype\n\n"; 
system "cat /home/cvsview/$path";

