#!/usr/local/bin/perl
#
# show history database of ~/.netscape/history.db for ebw3 result
#
# Copyright (C) 1999 Taiji Yamada

$history_list = "./history-db-list";

$id = "/jis/g0/0/[12]/2/search/";

if ($ENV{"SERVER_PROTOCOL"}) {
  print "Content-type: text/html\n\n";
}

$argc = 0;
foreach $argv (@ARGV) {
  $argv =~ s/%([0-9a-fA-F][0-9a-fA-F])/pack("C",hex($1))/eg;
  $argv =~ s/\\(.)/$1/g;
  $ARGV[$argc++] = $argv;
}

$filter_fgrep = "";
$filter_grep = "";
$filter_egrep = "";
$filter_misc = "";
require 'getopts.pl';
&Getopts('f:g:e:s:d:a:t:');
$filter_fgrep = "|/bin/env LANG=ja /bin/fgrep '$opt_f'" if ($opt_f);
$filter_grep = "|/bin/grep '$opt_g'" if ($opt_g);
$filter_egrep = "|/bin/egrep '$opt_e'" if ($opt_e);
$filter_misc = "|/bin/sort $opt_s" if ($opt_s);

$filters = "$filter_fgrep$filter_grep$filter_egrep$filter_misc";

$id = "$opt_d" if ($opt_d);

if ($usr = $ENV{"SCRIPT_NAME"}) {
  $usr =~ s/\/~([^\/]+).*/\1/g;
  $HOME = "/home/$usr";
} else {
  $HOME = $ENV{"HOME"};
}

print <<EOF;
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=euc-jp">
<TITLE>SHOW HISTORY of EBW3 Result</TITLE>
</HEAD>
<BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#0000EE" VLINK="#551A8B" ALINK="#FF0000">
<H1>SHOW HISTORY of EBW3 Result</H1>
EOF

if ($ARGV[0] eq '-') {
  $in = 'STDIN';
} else {
  $in = 'history';
  open($in, "/bin/env HOME=$HOME $history_list$filters|");
}
$id =~ s/\//(%2F|\\\/)/g;
while (<$in>) {
  if (!$opt_a && !$opt_t) {
    ($url,$title) = /([^\t]*)\t([^\t]*)/;
  } else {
    ($url,$title,$last,$first,$expire,$count) = /([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)/;
    next if ($opt_a && $opt_a gt $last);
    next if ($opt_t && $last gt $opt_t);
  }
  next if ($url !~ /ebw3/);
  next if ($title !~ /Result/ && $title !~ /Honbun/);
  next if ($url !~ /$id/ );
  ($current) = $url =~ /^(.*)\/cdsearch\.cgi/;
  open(GET,"wget -O - '$url'|nkf -e|");
  $contents = 0;
  while ($get=<GET>) {
    if (!$contents && $get =~ /^<HR>/i) {
      $contents = !0;
    }
    if ($contents && ($get=~/^<P>/i||$get=~/<HR><UL>/i||$get=~/<\/BODY>/i)) {
      $contents = 0;
      last;
    }
    if ($contents && $get =~ /<H2>³ºÅö¹àÌÜ°ìÍ÷/) {
      $contents = 0;
      last;
    }
    if ($contents) {
      if ($get =~ /src=\"cdsearch.cgi/) {
	$get =~ s/cdsearch\.cgi/$current\/cdsearch\.cgi/;
      }
      print "$get";
    }
  }
  close(GET);
}
close($in) if ($in ne 'STDIN');

print <<EOF;
</BODY>
</HTML>
EOF
