#!/usr/local/bin/perl -w
###########################################
# kindle-connected
# Mike Schilli, 2012 (m@perlmeister.com)
###########################################
use strict;
use local::lib qw(/home/mschilli/perl5);
use Log::Log4perl qw(:easy);
use POSIX;
use DBI;

my $run_as = "mschilli";
my $clip_path = 
"/media/Kindle/documents/My Clippings.txt";

BEGIN {
    use FindBin qw($RealBin);
    chdir $RealBin;
}
use ClippingsParser;

my $logfile = "/var/log/kindle.log";

Log::Log4perl->easy_init({ 
  file  => ">>$logfile", 
  level => $DEBUG,
});

my ( $name, $passwd, $uid, $gid ) = 
  getpwnam( $run_as);

chown $uid, $gid, $logfile or 
  LOGDIE "Cannot chown $logfile: $!";
chmod 0644, $logfile or
  LOGDIE "Cannot chmod $logfile: $!";

POSIX::setuid( $uid );

my $pid = fork();
die "fork failed" if !defined $pid;
exit 0 if $pid; # parent

  # wait until kindle root dir is mounted
for( 1..10) {
    if( -f $clip_path) {
        last;
    } else {
        DEBUG "Waiting for $clip_path";
        sleep 5;
        next;
    }
}

LOGDIE "$clip_path not found" 
  if !-f $clip_path;

my $dbh = DBI->connect(
  "dbi:SQLite:highlights.sqlite", "", "",
  { RaiseError => 1, PrintError => 0 } 
);

open my $fh, "<", $clip_path or
    LOGDIE "Cannot open $clip_path ($!)";

my $cp = ClippingsParser->new();

my $items_added = 0;

$cp->parse_fh( $fh, sub {
  my( $type, $loc, $author, $title, 
      $when, $text ) = @_;

  my $sth = $dbh->prepare(
    "INSERT INTO seen VALUES (?, ?, ?)");

  eval {
      $sth->execute( $type, $loc, $title );
  };

  return if $@; # most likely a dupe

  $sth = $dbh->prepare( "INSERT INTO " .
   "highlights VALUES (?, ?, ?, ?, ?, ?)");
  $sth->execute( $type, $loc, $author, 
                 $title, $when, $text );
  $items_added++;
} );

INFO "$items_added items added";
close $fh;
