#!/usr/bin/perl
use Net::Delicious;
use Log::Dispatch::Screen;
use DBI;

my $del = Net::Delicious->new({user => "USERNAME", pswd => "PASSWORD"});

# Set up database connection
$dbh = DBI->connect('DBI:mysql:insipid', 'DBUSER', 'DBPASS') || die "Could not connect to database: $DBI::errstr";

# Get the bookmarks
my $bookmarks_qry = $dbh->prepare("SELECT id, url, title, description FROM bookmarks WHERE (delicious = 0 OR delicious is null) ORDER BY date DESC");
$bookmarks_qry->execute();

while (my $ref = $bookmarks_qry->fetchrow_hashref()) {
	$del_tags = "";
	$del_url = $ref->{'url'};
	$del_title = $ref->{'title'};
	$del_description = $ref->{'description'};

	# Get the associated tags
	my $tags_qry = $dbh->prepare("SELECT bookmark_id, name FROM bookmark_tags INNER JOIN tags ON bookmark_tags.tag_id=tags.id WHERE bookmark_id=".$ref->{'id'});
	$tags_qry->execute();

	while (my $tags_ref = $tags_qry->fetchrow_hashref()) {
		$del_tags .= $tags_ref->{'name'} . " ";
	}

	# Strip whitespace from beginning and end of tags
	$del_tags =~ s/^\s+//;
	$del_tags =~ s/\s+$//;

	# Insert tag into Delicious
	my $return = $del->add_post({
		url => $del_url,
		description => $del_title,
		extended => $del_description,
		tags => $del_tags,
		dt => $dt,
	});

	print "Inserted: $del_title\n";
}

$bookmarks_qry->finish();

$dbh->disconnect();

