#!/usr/bin/perl
use strict;
use warnings;
use FindBin;
use DBI;
use MIME::Base64;
use File::MMagic;
use Path::Class;

my $DBHOME=dir($FindBin::Bin)->parent->file('bookmarks.db');
my $db=DBI->connect("dbi:SQLite:$DBHOME");

my $magic=File::MMagic->new();

my $sth=$db->prepare('select pk,icon from links');
$sth->execute();
my ($pk,$icon,$type);
my @to_clean=();my %to_update;
while (($pk,$icon)=$sth->fetchrow_array()) {
    $icon=decode_base64($icon);
    $type=$magic->checktype_contents($icon);
    if ($type =~ /^text/) {
        push @to_clean,$pk;
    }
    else {
        $to_update{$pk}=$type;
    }
}

$sth=$db->prepare(q{update links set icon='' where pk=?});
for $pk (@to_clean) {
    $sth->execute($pk);
}
$sth=$db->prepare(q{update links set icon_type=? where pk=?});
while (($pk,$type)=each %to_update) {
    $sth->execute($type,$pk);
}

$db->disconnect;
