#! /usr/bin/perl

# shotwell-tag
#
# Tags files specified by filename in shotwell. Handy for 
# getting round shotwell's attempts at hiding the filesystem.
# 
# Avi 2011

use strict;
use DBI;

my $file = shift;
my $tag = shift;

if ($tag !~ /.+/){
        print "Usage:\n\n\tshotwell-tag [file] [tag]\n\n";
        print "Tags [file] with [tag] in shotwell's db\n";
        exit 1;
}

my $dbfile = $ENV{'HOME'}."/.shotwell/data/photo.db";
my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","");

# Each tag has a string of photo 'ids'. These are generated
# by taking the ID of the photo from PhotoTable, representing
# it in hex, padding that out to 16 characters with leading 
# zeroes and then appending it to the string 'thumb'
my $sth = $dbh->prepare("select id from PhotoTable where filename='$file'");
$sth->execute();
my $row = $sth->fetch;
my $photoId = $row->[0];
unless($photoId =~ /\d+/){print "$file is not in shotwell library\n"; exit 0;}
my $hexPhotoId = sprintf("%x", $photoId);
my $thumbString = "thumb".sprintf('%016s', $hexPhotoId);

$sth = $dbh->prepare("select id from TagTable where name='$tag'");
$sth->execute();
$row = $sth->fetch;
my $tagId = $row->[0];
unless($tagId =~ /\d+/){
	print "Creating tag $tag\n";
	my $sth = $dbh->prepare("insert into TagTable (name) values('$tag')");
	$sth->execute;
}

$sth = $dbh->prepare("Select photo_id_list from TagTable where name='$tag'");
$sth->execute();
$row = $sth->fetch;
my $photoList = $row->[0];
if($photoList !~ /,$/ && $photoList =~ /._/){
	$photoList.=',';
}
if($photoList =~ /$thumbString/){
	print "$file is already tagged with $tag\n";
	exit 0;
}else{
	$photoList.=$thumbString.',';
	$sth = $dbh->prepare("update TagTable set photo_id_list = '$photoList' where name='$tag'");
	$sth->execute;
	print "tagged $file with $tag\n";
	exit 0;
}
