#!/usr/bin/perl

# exif_touch changes the modified date of a file to match exif information
# Copyright (C) 2005  Mike Lococo
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
# USA.

use strict;
use warnings;

my $imgname = '';
my $dirname = '';
my $success = '';
if (!defined($ARGV[0])) {exit display_error();}
my $input = $ARGV[0];

# Process a single file
if (-f $input) {
 $imgname = $input;
 $success = exif_touch($imgname);
 if ($success ne "0") {print $success;}
}
# Process a directory of files
if (-d $input) {
 $dirname = $input;
 $dirname =~ s/\/$//;
 opendir(IMGDIR, $dirname)
  or die "Can't open directory: $dirname\n";
 while ($imgname = readdir IMGDIR) {
  next unless $imgname =~ /\.jpg|\.JPG|\.jpeg|\.JPEG$/; # operate only on jpgs
  $imgname = $dirname . '/' . $imgname;
  exif_touch($imgname);
 if ($success ne "0") {print $success;}
 }
 closedir(IMGDIR);
}
if ((!-f $input) && (!-d $input)) {
 print "ERROR: No such file or directory.\n\n";
 exit display_error();
}

sub exif_touch {
 # Accepts a filename, gets the exif "image created" time using the external
 # program "exiftime", and sets the modified date with "touch -t"
 #
 # Format given by exiftime:
 #    "Image Generated: YYYY:MM:DD HH:MM:SS\n"
 # Format needed by touch -t:
 #    "YYYYMMDDHHMM.SS"
 my $imgname = $_[0];
 my $imgtime = `exiftime -tc '$imgname'`;
 if ($? != 0) {return "Warning: \"exiftime\" cannot open $imgname\n";}
 else {
  $imgtime =~ s/Image Created: //;  # Strip leading text
  $imgtime =~ s/:(..)$/\.$1/;       # Change final : to .
  $imgtime =~ s/://g;               # Strip :'s
  $imgtime =~ s/ //g;               # Strip spaces
  chomp($imgtime);                  # Strip newline
  system ("touch", "-t" ,$imgtime, $imgname);
  if ($? != 0) {return "Warning: \"touch\" cannot open $imgname\n";}
  else {return 0;}
 }
}

sub display_error {
 print "Used to set the \"modified date\" of a jpg to match the \"Image Created\"\n";
 print "date in the EXIF headers.  Relies on the external the external programs\n";
 print "\"touch\" and \"exiftime\".\n";
 print "\n";
 print "Examples:\n";
 print "set_photo_date.pl filename\n";
 print "set_photo_date.pl /directory/of-files/to-process/\n";
}
