#! /usr/local/bin/python -O


#Subject: Netscape history file dumper
#Author: Oleg Broytmann <phd2@earthling.net>
#
#based on program
#From: Hannu Krosing <hannu@sid.trust.ee>
#
#Does anybody know what the other two integer fields after dates mean ?


import sys, os, string, time, struct, bsddb
from getopt import getopt


silent = 0
usage = 1

def error(error_str):
   if not silent:
      sys.stderr.write("%s\n" % error_str)
   if usage:
      sys.stderr.write("Usage: %s [-s] [-o outfile]\n" % sys.argv[0])
   sys.exit(1)


found = 0
for hist_filename in ("history.dat", "history.db", "netscape.hst"):
   if os.path.exists(hist_filename):
      found = 1
      break

if not found:
   error("Cannot find history file")


outfile = sys.stdout
optlist, args = getopt(sys.argv[1:], "so:")

for _opt, _arg in optlist:
   if _opt == '-s':
      silent = 1
   if _opt == '-o':
      outfile = open(_arg, 'w')
try:
   del _opt, _arg
except NameError:
   pass

if args:
   if len(args) >= 1:
      error("Too many parameters")


def fmt_time(int):
    return '%4d-%02d-%02d %02d:%02d:%02d' % time.localtime(int)[:6]

def mk_tuple(key,value):
    return (key,) + struct.unpack('<llll',value[:16]) + (value[16:],)

def print_tuple(tuple):
    key,t1,t2,v1,v2,v3 = tuple
    list = [key[:-1], fmt_time(t1), fmt_time(t2)]
    list = list + map(str,[v1,v2,v3])
    outfile.write( string.join(list,'\t') + '\n' )

usage = 0

try:
   history = bsddb.hashopen(hist_filename)
except:
   error("Error opening history file")

try:
   key, value = history.first()
except:
   error("Error finding first key")

while 1:
    tup = mk_tuple(key,value)
    print_tuple(tup)
    try:
        key, value = history.next()
    except: # all keys exhausted
        break

outfile.close()
history.close()
