#!/usr/local/bin/perl
# (c) 1998 Eddie Kohler.
# This file may be freely distributed and modified as long as this copyright
# notice is kept intact.

#####
# ERROR_EXIT
# &error_exit($title, $message...) prints an HTML document summarizing the
# error and exits.

sub error_exit {
  my $title = @_[0];
  my $message = join('', @_[1..$#_]);
  print <<"EOD;";
Content-type: text/html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Plaintextify Error</title></head>
<body>

<h1>$title</h1>

<p>$message

</body>
</html>
EOD;
  exit 0;
}


#####
# URL_TRANSLATE

sub url_translate {
  my($x) = $_[0];
  $x =~ s/\+/ /g;
  $x =~ s/%(\w\w)/pack('C', hex($1))/eg;
  $x;
}

sub process_query {
  my($q) = $_[0];
  local($_);
  while ($q =~ /^\&?([^\&]+)(.*)/) {
    $_ = &url_translate($1);
    $q = $2;
    if (/^lineno=(\d+)$/) {
      $line_numbers = $1;
    } elsif (/^lineno$/ || /^ln$/) {
      $line_numbers = 1;
    } elsif (/^file=(.*)$/) {
      $doc = $1;
    } elsif (!/=/) {
      $doc = $_;
    } else {
      &error_exit('Bad Query', <<"EOD;");
I don't understand part of your query -- specifically, the ``<tt>$_</tt>''
part.
EOD;
    }
  }
}

##########
# THE MAIN PROGRAM
##

##
# INITIALIZATION & READING
&process_query($ENV{'QUERY_STRING'});
&error_exit('No Query', 'You have to say which document to plaintextify.')
  if !defined $doc;
$doc =~ tr/'"`*?\\\$()&|!;<>{}\000-\032\177-\377/./;
$input_doc = $doc;
if ($doc =~ m|^~eddietwo/|) {
  $doc = glob($doc);
} else {
  $doc =~ s(^/)();
  $doc = "/usr/local/apache/htdocs/" . $doc;
}
&error_exit('Bad Document', "Can't open file $doc.")
  if !open(DOC, $doc);

if ($line_numbers) {
  print <<"EOD;";
Content-type: text/html\r
\r
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>$input_doc</title>
<style type="text/css"><!--
A { color: #999999 }
--></style>
</head>
<body>
<h1><code>$input_doc</code></h1>
<a href="/plainify.cgi?$input_doc"><i><font color=blue>(no line numbers)</font></i></a>
<pre>
EOD;
  $line = 1;
  while (<DOC>) {
    s|\t|' ' x (((length($`) + 8) & 0xFFF8) - length($`))|e while /\t/;
    s|&|&amp;|g;
    s|<|&lt;|g;
    s|>|&gt;|g;
    printf "<a name=$line>%4d:</a> ", $line;
    print $_;
    $line++;
  }
  print <<"EOD;";
</pre>
</body>
</html>
EOD;

} else {
  print "Content-type: text/plain\r\n\r\n";
  print while <DOC>;
}

close DOC;
