#!/usr/bin/perl
use strict;

my $data_dir_name = '../data/';

my $start = 0;
if ($ENV{PATH_INFO} =~ m#^/(\d+)-$#) {
  $start = $1;
}

sub htescape ($) {
  my $s = $_[0];
  $s =~ s/&/&amp;/g;
  $s =~ s/</&lt;/g;
  $s =~ s/>/&gt;/g;
  $s =~ s/"/&quot;/g;
  return $s;
} # htescape

print qq[Content-Type: text/html; charset=utf-8

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/www/style/html/xhtml">
<style>
.uri {
  display: block;
  width: 6em;
  height: 6em;
  overflow: auto;
}
</style>
</head>
<body>
<table>
<thead>
<tr><th scope="row">#</th><th scope="row">URI</th>
<th scope="row">Time</th><th scope="row">Tags</th></tr>
</thead>
];

my $i = int ($start / 1000);
D1: {
  my $d1_dir_name = $data_dir_name.$i.'/';
  last D1 unless -d $d1_dir_name;

  my $d1_index_file_name = $d1_dir_name . 'index.dat';
  if (-f $d1_index_file_name) {
    open my $d1_index_file, '<', $d1_index_file_name 
        or die "$0: $d1_index_file_name: $!";
    while (<$d1_index_file>) {
      if (/^(\d+)\t([^\t]+)\t(\d+)\t(.+)/) {
        my ($num, $uri, $date, $tags) = ($1, $2, $3, $4);
        next if $num < $start;
        print qq[<tr><th scope="row"><a href="../list/$num-">#</a> <a href="../../data/@{[int ($num / 1000)]}/@{[$num % 1000]}">$num</a><td><code class="uri">];
        print htescape ($uri), qq[</code><td>];
        print htescape (scalar localtime $date), qq[<td>];
        print join ' ', map {htescape ($_)} split /;/, $tags;
      }
    }
  }

  $i++;
  redo D1;
} # D1

print qq[</table></body></html>];

