# Album Plugin: images/autorot
# For info: 'album -plugin_info images/autorot'
# For usage:  'album -plugin_usage images/autorot'
use strict;		# Not required, but recommended

my $DESCRIPTION = << 'DESCRIPTION';
Autorotates images based on EXIF captions.
Uses 'jhead' program, and does rotation the first time it sees the image.
Idea credit:  Fridtjof Busse, who is too lazy to type jhead himself.  :)

Significant speedup when images already exist by Simon Oosthoek.

DESCRIPTION

sub start_plugin {
	my ($opt) = @_;

	my $ret = {
		author      => 'David Ljung Madison, Simon Oosthoek',
		href        => 'http://MarginalHacks.com/',
		version     => '1.0',
		description => $DESCRIPTION,
	};


	# Setup the hooks
 	album::hook($opt, 'thumbnail', \&thumbnail);
 	album::hook($opt, 'medium',  \&medium);

	return $ret;
}


sub medium {
	my ($opt, $hook,  $dir, $obj, $file, $full_path) = @_;

	# Generate the name for the medium file, assuming some things (.med for
	# medium indication, nothing has changed in the settings for medium,
	# etc. this is a HACK!)
	my $medname = "$dir/" . $opt->{dir} ."/$file";
	$medname =~ s/\.(jpg)$/.med.$1/i;
	# if the guessed medium file actually exists, assume it has been
	# created ok, return that name so album won't touch it
	# otherwise, return undef, which causes album to regenerate it
	if ( -f $medname ) {
		return $medname;
	} else {
		return undef;
	}
}

sub thumbnail {
	my ($opt, $hook,  $dir, $obj, $file, $full_path, $default) = @_;

	# Only for jpgs/jpegs
	return $default unless $file =~ /\.jpe?g$/i;

	# If the thumbnail exists, don't rotate. return $default to prevent regeneration of thumbnail
	return $default if -f $default;

	# Do we have jhead?
	return undef unless $opt->{jhead};

	# Quasi-bug - if we erase the thumbnail, then we'll call jhead again,
	# but this is correct if inefficient since jhead fixes the EXIF orientation.
	system($opt->{jhead},'-autorot',"$dir/$file");
	album::perror($opt,"Couldn't autorot image? [$dir/$file]\n") if $?;

	# Still return undef, we haven't actually generated the thumbnail.
	return undef;
}


# Plugins always end with:
1;
