#!/usr/bin/perl
# ABSTRACT = 'automatically rotate jpg image guided by exif data'
use File::Which;
use strict;
use Cwd;
use String::ShellQuote 'shell_quote';
use Getopt::Std::Strict 'hvn';
our $VERSION = sprintf "%d.%02d", q$Revision: 1.2 $ =~ /(\d+)/g;
$opt_h and print STDERR usage() and exit;
$opt_v and print "$VERSION\n" and exit;

map { File::Which::which($_) or die("fan't find which '$_'") } qw/mogrify exiftool/;

sub usage {q{imgautorotate [OPTION].. IMAGE..
automatically rotate jpg image guided by exif data

   -h          help
   -n          just show the shell commands
   -v          version

Try 'man imgautorotate' for more info.
}}


my $fails=0;
for (@ARGV){
   my $f = Cwd::abs_path($_) or die;
   $f=~/jpe?g$/ or next;
   -f $f or next;
   my $s = shell_quote($f);
   my $o = `exiftool -Orientation  $s`;
   chomp $o;
   $o or warn("can't get orientation for $s") and $fails++ and next;

   my @cmds;

   if ($o=~/Rotate 90 CW/){
      @cmds = (
         "mogrify -rotate 90 -quality 95 $s",
         "exiftool -Orientation='normal' $s",
      );

   }
   elsif ($o=~/Rotate 90 CCW/){
      @cmds = (
         "mogrify -rotate -90 -quality 95 $s",
         "exiftool -Orientation='normal' $s",
      );
   }

   if ( $opt_n ){
      map { print "$_\n" } @cmds;
   }
   else {
      map { system($_) == 0 or die($!) } @cmds;
   }

}

exit $fails;
   



__END__

=pod

=head1 NAME

imgautorotate - automatically rotate jpg image guided by exif data

=head1 DESCRIPTION

Uses exiftool to see if an image has orientation set to something.
It will use mogrify to alter the original images.
Non jpeg files (regex) are skipped.
Any images we can't get info for are failures. The exit code is how
many failures we have. Skipped arguments are not deemed failures.

=head1 USAGE

imgautorotate [OPTIONS].. IMAGEFILE..

   -h          help
   -n          just show the shell commands
   -v          version


=head2 USAGE EXAMPLES

   imgautorotate ./images/*jpg

=head1 SEE ALSO

exiftool
mogrify

=head1 AUTHOR

Leo Charre leocharre at cpan dot org

=head1 LICENSE

This package is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e., under the terms of the "Artistic License" or the "GNU General Public License".

=head1 DISCLAIMER

This package 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.

=cut

