#!/usr/bin/perl
# CHANGE THIS to correct path (type 'which perl' to get it).
# mac.pl - CGI-Script (v0.2a) by A. Farber, converts WWW-documents
# from Mac to KOI8-r 'on the fly'. Feel free to modify and use it,
# but please put a link to my 'Russian Literature on the Net' page at:
# http://iaiwww.uni-muenster.de/cgi-bin/simplex/lat/lit.html

$SIG{'ALRM'} = 'timeout';
alarm 1800;

$Path = '/home/www/russian'; # directory, where files a located
# CHANGE THIS to the full (UNIX) path to the directory where your
# russian (KOI8-r) WWW-documents are kept (type 'pwd' to get it).

$WWWPath = '~moshkow/russian'; # URL (without hostname), where documents
                               # are located from viewer's point of view

$DefPage = 'index.html';
# CHANGE THIS to the default WWW-page name at your WWW-server
# (sometimes it is 'home.html' or 'welcome.html').

# $|=1; # Try uncommenting this line if the script stays in memory

$Path .= $ENV{'PATH_INFO'};

if ($Path =~ /\.\./) {	# there is a '..' - someone tries to break in?
	die "Achtung! $ENV{'REMOTE_ADDR'} tries to get $Path";
}

if ($Path =~ /\/$/) {	# there is a '/' at the end
	$Path .= $DefPage;
}

open(DOCUMENT, $Path) || die "Can't open $Path";

if ($Path =~ /\.html?$/i) {	# there is a '.htm' or '.html' at the end
	print "Content-type: text/html\n";
}elsif ($Path =~ /\.txt$/i){
	print "Content-type: text/plain\n";
}else { # if we dont know how handle this format,
        # relocate viewer to real location of file
	print "Location: http:$WWWPath$ENV{PATH_INFO}\n\n";
        exit 0 ;
}

print 'Content-Length: ', -s $Path, "\n"; # insert only if it's the real size

($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime((stat($Path))[9]);
$wday = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')[$wday];
$mon  = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec')[$mon];
printf "Last-Modified: %s %s  %d %.2d:%.2d:%.2d 19%.2d\n\n", ($wday, $mon,
$mday, $hour, $min, $sec, $year);

while (<DOCUMENT>) {            # there must be no break in the next line!
	tr/\xC0-\xFF/\xFE\xE0\xE1\xF6\xE4\xE5\xF4\xE3\xF5\xE8-\xEF\xFF\xF0-\xF3\xE6\xE2\xFC\xFB\xE7\xF8\xFD\xF9\xF7\xFA\x9E\x80\x81\x96\x84\x85\x94\x83\x95\x88-\x8F\x9F\x90-\x93\x86\x82\x9C\x9B\x87\x98\x9D\x99\x97\x9A/;
	print;
}

close(DOCUMENT);
exit(0);

sub timeout {
	die "Timeout while printing $Path";
}