#!/usr/bin/perl

use strict;

use CGI;
use DiffPrinter::raw;
use DiffPrinter::html;
use PatchIterator::RawPatchIterator;
use PatchIterator::FixPatchRootIterator;
use PatchIterator::AddCVSContextIterator;
use PatchIterator::NarrowPatchIterator;

my $CVSROOT = ':pserver:jkeiser%netscape.com@cvs.mozilla.org:/cvsroot';
my $TMPDIR = "/tmp";
my $BONSAI_URL = "http://bonsai.mozilla.org";
my $LXR_URL = "http://lxr.mozilla.org/mozilla";
my $LXR_ROOT = "mozilla/";

my $p = new CGI();
#
# Parameters:
# format=raw|html
# context=patch|file|0-n
# collapsed=0|1
#

my $iter = new PatchIterator::RawPatchIterator;
$iter->target(new PatchIterator::FixPatchRootIterator($CVSROOT));
my $last_iter;
if (defined($p->param('context')) && $p->param('context') ne "patch") {
  $iter->target->target(
      new PatchIterator::AddCVSContextIterator($p->param('context'),
                                               $CVSROOT, $TMPDIR));
  $last_iter = $iter->target->target;
} else {
  $last_iter = $iter->target;
}

if ($p->param("format") eq "raw") {
  print $p->header(-type => 'text/plain',
                   -expires => '+3M');
  $last_iter->target(new DiffPrinter::raw());
} else {
  print $p->header(-expires => '+3M');
  $last_iter->target(new DiffPrinter::html(scalar($p->param('collapsed')),
                                           $BONSAI_URL, $LXR_URL, $LXR_ROOT));
  print "<html>\n";
  print "<head>\n";
  print "<title>Patch Viewer</title>\n";
  print $last_iter->target->head_section();
  print "</head>\n";
  print "<body onload=\"", $last_iter->target->onload(), "\">\n";

  # Raw format link
  my $p_copy = new CGI($p);
  $p_copy->param('format', 'raw');
  print '<a href="', $p_copy->self_url, '">Show Raw</a> | ';

  print "<span style='font-weight: bold'>Context:</span> ";

  # No context link
  $p_copy = new CGI($p);
  $p_copy->delete('context');
  print '<a href="', $p_copy->self_url, '">Patch</a> | ';

  # Full context link
  $p_copy = new CGI($p);
  $p_copy->param('context', 'file');
  print '<a href="', $p_copy->self_url, '">File</a> | ';

  # textbox for context
  print '<form style="display: inline">';
  foreach my $param ($p->param) {
    next if $param eq "context";
    $p->hidden($param, $p->param($param));
  }
  print '<input type="text" name="context" value="3" size="5"></form>', "\n";
}

# Actually print out the patch
$iter->iterate_file("Restore.patch");

if ($p->param("format") ne "raw") {
  print "</body>\n";
  print "</html>\n";
}
