#!/usr/bin/perl

# $Id:$ 
# Philip Shuman    philip at shuman dot org
# Based on rename.pl, merged with file-pix.pl from
# http://alumnus.caltech.edu/~copeland/work/pix.html

# ORIGINAL CREDITS:
# author : sergey s prozhogin (ccpro@rrelaxo.org.ru)
# script renames file by EXIF date
# for information start perl rename.pl
#
# v 1.3 May-20-2004
# 

use strict;
use Image::EXIF;
use Date::Parse;
use Data::Dumper;
use Getopt::Std;

use vars qw/ $opt_p /;
getopts('p');

#my @list = `ls -1 OSW*.JPG sentinel*.jpg* [PpDJ]*.[jJ][pP][gG] IMG*.JPG IMG*.jpg 100*.jpg 100*.JPG 00*.jpg 00*.JPG`;
my @list = `ls -1 img_*.jpg OSW*.JPG sentinel*.jpg* [PpDJ]*.[jJ][pP][gG] IMG*.JPG IMG*.jpg 100*.jpg 100*.JPG 00*.jpg 00*.JPG`;

my $exif = new Image::EXIF;

for my $fname (@list)
{
	chomp $fname;
   print "Reading $fname\n";

	$exif->file_name($fname);
	my $data = $exif->get_all_info();

	if ($data)
	{
		my $timestamp = $data->{image}->{'Image Created'} || $data->{other}->{'Image Generated'} || $data->{image}->{'Image Digitized'} || $data->{image}->{'DateTimeOriginal'};
      print "  Image Created =   " . $data->{image}->{'Image Created'} . "\n";
      print "  Image Generated = " . $data->{image}->{'Image Generated'} . "\n";
      print "  Image Digitized = " . $data->{image}->{'Image Digitized'} . "\n";
      print "  DateTimeOriginal= " . $data->{image}->{'DateTimeOriginal'} . "\n";

      my $re = "(\\d\\d\\d\\d):(\\d\\d):(\\d\\d) (\\d\\d):(\\d\\d):(\\d\\d)";
      die "bad date format in $_" unless $timestamp =~ /$re/o;

      # This will be your new file format. The following will produce:
      # 2005_04_14-22_24_59.jpg
      my $new_file = "$1_$2_$3-$4_$5_$6"; 

		my $count = 1;

      if( -r "$new_file.jpg") {
         warn "file $new_file.jpg already exists";

         while (-f "$new_file-$count.jpg")
         {
            $count ++;
         }
         $new_file = "$new_file-$count";
      }
      $new_file .= ".jpg";

      if( -r "$new_file") {
         # final sanity check, should never run.
         warn "file $new_file already exists";
      }
      else
      {
         if ($opt_p) {
            print "#mv -iv ";
            print "$fname ";
            print "$new_file\n";
         }
         else {
            print "Renaming $fname to $new_file\n";
            rename $fname, $new_file;
         }
      }
	}
}
