#!/usr/bin/env perl

$arg = shift;

# standard prefix
$viewname = "/view/doc";
$prefix = "/vob";
$mailto = "Marc Girod";
$mailaddr = "girod\@shire.ntc.nokia.com";
$ENV{PATH} = "/opt/rational/clearcase/bin:/bin";

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

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

if (! -r $arg) {
  errorpage("Can't read '$arg'.\n");
}

$comment = `cleartool describe -fmt "%c" $arg 2>&1`;
$changes = `cleartool diff -pred -ser $arg 2>&1`;

# Changes can contain SGML code which should not be formatted
$changes =~ s/</\&lt;/g;
$changes =~ s/>/\&gt;/g;

$title = "Version information for $arg";
$now = localtime();

print <<HTML;
Content-type: text/html

<html>
<head>
<title>$title</title>
</head>
<body>
<h1>$title</h1>
$now
<hr>

<h2>Comment</h2>
<blockquote>$comment</blockquote>

<h2>Changes from previous version</h2>
<blockquote><pre>$changes</pre></blockquote>

<hr>
<address>This page is automagically generated. Mail your remarks to
<a href="mailto:$mailaddr">$mailto</a></address>

</body>
</html>
HTML

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);
}
