#! /usr/bin/perl -w
# @(#$Id: rclimg,v 1.2 2007/10/02 13:56:42 dockes Exp $  (C) 2007 Cedric Scott
#######################################################
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
######################################################

#
# rclimg: extract image tags with exiftool and convert the data to html for
# recoll indexing.
#

#
# maps image file tags to xapian tags
#
$tagMap = {
	'subject' => 'subject',
	'title' => 'title',
	'headline' => 'title',
	'caption' => 'caption',
	'caption-abstract' => 'caption',
	'author' => 'author',
	'creator' => 'creator',
	'from' => 'from',
	'keywords' => 'keywords',
	'keyword' => 'keyword',
	'tag' => 'tag',
};

# set to non-zero if tags which map to xapian tags are to output
# in the body as well as the header
#
$headAndBody = 1;

# xapianTag
# returns a xapian tag to be used for this tag
#
sub xapianTag {
	my $imgtag = shift;
	while ( ( $tagre, $xapiantag) = each %{$tagMap} ) {
		return $xapiantag  if $imgtag =~ /$tagre/i;
	}
	return undef;
}

#
# start here
#
use Image::ExifTool qw(:Public);

$imageFile = shift;
$imageFile = '-' if $imageFile eq '';
unless ( open(IMGF, $imageFile)  ) {
	print STDERR "$0: can't open file $imageFile\n";
	exit(1); # file doesn't exist or can't be read
}
$info = ImageInfo(\*IMGF);
die unless $info;
$fields = [];
$other = [];
$titleHtmlTag = "";
foreach $tagname ( sort keys %{$info} ) {
	$xapiantag = xapianTag($tagname);
	if (defined $xapiantag ) {
		push @{$fields}, [ $xapiantag, $info->{$tagname} ];
		$titleHtmlTag = "<title>$info->{$tagname}</title>" if $xapiantag eq 'title';
		push @{$other}, [ $tagname, $info->{$tagname} ] if $headAndBody;
	} else {
		push @{$other}, [ $tagname, $info->{$tagname} ];
	}
}
print "<html>\n<head>\n$titleHtmlTag\n";
print "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\">\n";
foreach $tagpair ( @{$fields} ) {
	($tagname, $value) = @{$tagpair};
	print "<meta name=\"$tagname\" content=\"$value\">\n";
}
print "</head><body>\n";
foreach $tagpair (@{$other} ) {
	($tagname, $value) = @{$tagpair};
	printf "%30s : %s<br>\n", $tagname, $value;
}
print "</body>\n</html>\n";
