#!/usr/bin/perl -w
#by Torben Menke
#http://www.entorb.net
# renames images so that date and time apear in the filename
# not recursive in subfolders, but scans the given folders for images
# works on .jpg, .jpeg files
# renames .jpeg -> .jpg
#
# REQUIRES exif (debian package or similar...)
`exif --version` or die;


#TODO
#make the putput nice (printf)

use strict;
use warnings;
use Time::Local;

my @dirs; #list of directories
my @files; #list of files
my $str;
my $countRenamed=0;

# in seconds
my $timeoffset = 0;


if (!@ARGV){
$dirs[0] = './';
}
else {
@_ = @ARGV;
# fills @files and @dirs
&separate_df(@_);
}

while (@dirs){
my $dir = shift @dirs;

opendir DIR, "$dir";
#my @new_items = sort (grep {!/^\.\.?$/ } readdir DIR);
my @new_files = sort (grep { /\.jpe?g$/ } readdir DIR);
closedir DIR;

foreach $_ (@new_files) {
$_ = "$dir/$_";
if (-f $_){
s#//#/#;
push (@files,$_);
}
}
}

foreach my $file (@files){
if (not -w $file) { # not writeable
print "File $file is write-protected, skipped!\n";
next;
}
my $filenew = '';
#extract the date and make it the prefixname
if ((my $prefix = &gettimedate($file)) ne ''){
$_ = $file;
if (m#^(.*/)[^/]+$#){
$filenew = $1;
}else {$filenew = '';}

m#([^/]+)$#;
$str = $prefix."_".$1;
$str =~ tr/[A-Z]/[a-z]/;
$str =~ s/\.jpeg$/\.jpg/;
$filenew .= $str;
if (-f $filenew){
print "File $filenew already exists, skipped!\n";
} else{
print "$file\t->\t$filenew\n";
rename $file, $filenew and $countRenamed++;
}
}else {print "NO MATCH: Got no date data!\n";}
}


sub gettimedate{
my $file = "@_";

#extract Date+Time using exif
$_ = `exif $file | egrep --text 'Date and Time \\(o'`;
print;
my ($sec,$min,$hour,$mday,$mon,$year) = (0,0,0,0,0,0);
s/^\D+//;
if (m/^(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D*/){
($sec,$min,$hour,$mday,$mon,$year) = ($6,$5,$4,$3,$2,$1);
$sec = $sec + 0;
$min = $min + 0;
$hour = $hour + 0;
$mday = $mday + 0;
$mon = $mon + 0;
$year = $year + 0;


if ($timeoffset != 0){
# month count starts at 0, year is saved as 1900 + x
($sec,$min,$hour,$mday,$mon,$year) = localtime(
$timeoffset +
timelocal($sec, $min, $hour, $mday, ($mon-1), ($year-1900))
);
$mon = $mon + 1 ;
$year = $year + 1900;
}



# print "STAMP: $year $mon $mday $hour $min $sec\n" ;
return &genfilename($year,$mon,$mday,$hour,$min);

}#if (m/^(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D*$/)
else {
# print "NO MATCH!!!\n";
return ''}
}


sub genfilename{
my @param = @_;
my $output = '';
my $count = 0;
foreach $_ (@param){
#add a ',' between date and time
if (++$count == 4) {
$output .= ','
}
if ($_>99){
$_ = $_ % 100; #modulo 100
}
if ($_<10){
$output.='0';
}
$output.=$_;
}
return $output;
}


sub separate_df{
foreach $_ (@_){
if (-d $_){
push @dirs, $_;
}
elsif (-f $_ && m/\.jpe?g$/i){ #jpg, jpeg
push @files, $_;
}
}
}


sub br{
print "\n";
}


print "Job done, $countRenamed files renamed\n";

Hope you found what you where looking for. Feel free to drop me a line
Torben