#!/usr/local/bin/perl -s
#
# list history database of ~/.netscape/history.db with Berkeley UNIX DB
#
# Copyright (C) 1999 Taiji Yamada

%month = ('Jan','1', 'Feb','2', 'Mar','3', 'Apr','4', 'May','5', 'Jun','6', 'Jul','7', 'Aug','8', 'Sep','9', 'Oct','10', 'Nov','11', 'Dec','12');

sub timestamp {
  local($time) = @_;
  $time = localtime($time);
  local($mon,$mday,$time,$year) = $time
      =~ /^\S+\s+(\S+)\s+(\d+)\s+(\d+:\d+:\d+)\s+(\d+)$/;
  sprintf("%4d/%02d/%02d %s", $year,$month{$mon},$mday,$time);
}

if (`uname -m` =~ /^sun/) {
  $history = $ENV{"HOME"}."/.netscape/history.dat";
} else {
  $history = $ENV{"HOME"}."/.netscape/history.db";
}
$history = $ARGV[0] if ($ARGV[0]);
if (`uname -m` =~ /^sun/) {
  $C = 1 if ($history =~ /\.dat$/);
}
if ($h) {
  print "usage: $0 [-l|-f|-c|-e|-a] [-T] [-C] [history.db|history.dat]\n";
  printf "\t-l: print last visit date\n";
  printf "\t-f: print first visit date\n";
  printf "\t-c: print visit count\n";
  printf "\t-e: print expire date\n";
  printf "\t-a: print all attributes\n";
  printf "\t-T: print all untitled URLs\n";
  printf "\t-C: change endian type of database file\n";
  exit;
}

use Fcntl;
use DB_File;
tie %history, DB_File, $history, O_RDONLY;

foreach $key (keys %history) {
  next if ($key !~ /^(http|ftp|file|gopher):[ -~]+\0$/i);
  ($last,$first,$count,$expire,$title) = unpack("LLLLa*", $history{$key});
  $url = $key;
  if ($l || $f || $e || $c || $a) {
    if (defined($C)) {
      $last = unpack("N",pack("V",$last));
      $first = unpack("N",pack("V",$first));
      $count = unpack("N",pack("V",$count));
      $expire = unpack("N",pack("V",$expire));
    }
    $last = timestamp($last);
    $first = timestamp($first);
    $expire = timestamp($expire);
  }
  $url =~ s/\0$//;
  $title =~ s/\0$//;
  next if (!defined($T) && $title eq "");
  print "$url\t$title";
  print "\t$last" if ($l || $a);
  print "\t$first" if ($f || $a);
  print "\t$expire" if ($e || $a);
  print "\t$count" if ($c || $a);
  print "\n";
}
