#!/usr/bin/perl -w
#
# $Revision: 1.5 $ $Date: 2009/09/24 17:05:08 $
# $Source: /home/vogelke/notebook/2008/0813/firefox-sqlite/RCS/fftoday,v $
# $Host: sys7.com $
# $UUID: 49d0e0ed-9d3d-3f60-bc4a-96dfa181c901 $
#
#<fftoday: print Firefox history from SQLite file.
# usage: fftoday DATE HISTORY
# where: DATE = a parseable date string indicating what day to look for.
#        HISTORY = SQLite file holding browser history.

use DBI qw(:sql_types);
use POSIX qw(strftime);
use Time::ParseDate;
use File::Copy;
use strict;

umask(022);

# Default date is today.

my ($d, $date);

if (@ARGV) {
    $date = shift(@ARGV);
    die "$date: invalid date.\n" unless $d = parsedate($date);
}
else {
    $d = time();
}

# Default source is $MOZILLA_HISTORY.

my $src = $ENV{'MOZILLA_HISTORY'};
my $dst = "/tmp/places$$";

if (@ARGV) {
    $src = shift(@ARGV);
    die "$src: not found\n" unless -f $src;
}

# We can't read the SQLite file while Firefox is running,
# so copy it elsewhere.

my $today = strftime("%Y-%m-%d", localtime($d));
copy($src, $dst) or die "can't create $dst\n";

# Prepare SQL statement to grab history.

my $dump = "SELECT moz_historyvisits.visit_date, moz_places.url
    FROM moz_places, moz_historyvisits
    WHERE moz_places.id = moz_historyvisits.place_id";

# Connect to the DB and run the statement.

my $dbh = DBI->connect("dbi:SQLite:$dst") or die "connect";
my $sth = $dbh->prepare("$dump");
$sth->execute();

# Read each time and URL.  Get today's entries.

my @row;

while (@row = $sth->fetchrow_array) {

    # Time is 8-byte floating point, and it includes microseconds,
    # so zap them by simple division.  I'm not sure that's strictly
    # correct, but answers match a regular dump from "places.sqlite".

    $d = int($row[0] / 1000000);
    $date = strftime("%Y-%m-%d %T", localtime($d));

    print substr($date, 11), " $row[1]\n"
      if $today eq substr($date, 0, 10);
}

unlink($dst) or die "can't remove $dst\n";
exit(0);
