#
# mknmz-wwwoffle
#
#    wwwoffle chache file filter
#
#    wwwofflecache.pl
#
#
# Copyright (C) 2000 WATANABE Yoshimasa <naney@naney.org>
#
# This file is part of the mknmz-wwwoffle.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# $Id: wwwofflecache.pl.in,v 1.4 2000/10/17 23:47:28 naney Exp $
#
#


package wwwofflecache;

require 'util.pl';
use File::Basename;
use strict;

BEGIN {
  if (1) {
    eval "use DB_File;";
    die $@ if ($@);
  }
}

sub mediatype()     { 'application/x-wwwoffle-cache'; }
sub recursive()     { 1; }
sub pre_codeconv()  { 0; }
sub post_codeconv() { 0; }

my $useDB = 0;
my $uriDB;
my %uriHash;

sub status()        {
  if (1 && $ENV{MKNMZ_WWWOFFLE_URI_DB}) {
    if ($uriDB = tie(%uriHash,
                     'DB_File',
                     $ENV{MKNMZ_WWWOFFLE_URI_DB},
                     O_RDONLY)) {
      $useDB = 1;
      util::vprint("Open URI Database: " . $ENV{MKNMZ_WWWOFFLE_URI_DB} . "\n");
    }
    else {
      $useDB = 0;
    }
  }
  return 'yes';
}

sub add_magic ($) {
  $_[0]->addMagicEntry("0 string HTTP/1 application/x-wwwoffle-cache");
}

sub _replaceCode {
  my $filename = shift;

  my ($name, $path) = fileparse($filename);
  if ($name =~ /^D/) {
    my $uname = $name; $uname =~ s/^D/U/;
    if ($useDB) {
      if (exists $uriHash{"$path$uname"}) {
        return $uriHash{"$path$uname"};
      }
    }
    unless(open(URLFILE, $path . $uname)) {
      util::vprint("Can not open URL file: $path$uname\n");
    }
    else {
      my $url = <URLFILE>;
      close URLFILE;
      $filename = $url;
    }
  }
  return $filename;
}

sub replaceCode {
  $_ = _replaceCode($_);
}

sub filter ($$$$$) {
  my ($orig_cfile, $contref, $weighted_str, $headings, $fields) = @_;

  util::vprint($$orig_cfile . "\n");
  #----- [url or data?] -----
  if ($$contref =~ m|^HTTP/|) {
    util::vprint("Processing wwwoffle cache file ...\n");

    #----- [delete http header] -----
    $$contref =~ s|^HTTP/1||;
    $$contref =~ s/^.*?\015\012\015\012//s;

    $$contref =~ s/^<!-- MHonArc v\d+\.\d+\.\d+ -->//;
  }
  else {
    $$contref = '';
  }

  return undef;
}

END {
  if ($useDB) {
    undef $uriDB;
    untie %uriHash;
  }
}

1;
