#!/usr/bin/perl -- # -*- Perl -*-

# Script for renaming raw image files with sub-second date/time
# stamp. Based on copycf script which is copyright by Norman Walsh
# (see below).

# Script for moving images from digicam media to the local filesystem
# version 0.1
# 2007-02-12
# Copyright (C) 2007 Norman Walsh
# Released under the GPL license
# http://www.gnu.org/copyleft/gpl.html

# NO WARRANTY: This works for me. I'm paranoid about losing images, so
# I think it's pretty conservative. But I don't claim it'll work for
# you. Maybe it will. Maybe it won't. Maybe it'll lose images. Maybe
# it'll cause your hair to fall out. I don't know and I'm not
# responsible.

use strict;
use vars qw($opt_h $opt_n);
use English;
use Image::ExifTool qw(ImageInfo %allTables);
use Getopt::Std;

my $usage = "Usage: $0 [-hn] file ...\n";

die $usage if ! getopts('hn') || $opt_h;

my $MOVE="/bin/mv";
my $EXIFTOOL="/usr/bin/exiftool";

foreach my $pgm ($MOVE, $EXIFTOOL) {
    die "Cannot find $pgm.\n" unless -x $pgm;
}

my @FILES = @ARGV;
foreach my $image (@FILES) {
    my $newName = dateTimeRename($image);
}

exit;

# ============================================================

sub dateTimeRename {
    my $image = shift;
    my $info = ImageInfo("$image");

    my $date = undef;
    if (exists $info->{'SubSecDateTimeOriginal'}) {
	$date = $info->{'SubSecDateTimeOriginal'};
    } elsif (exists $info->{'DateTimeOriginal'}) {
	$date = $info->{'DateTimeOriginal'};
    } elsif (exists $info->{'ModifyDate'}) {
	$date = $info->{'ModifyDate'};
    } else {
	warn "Cannot rename $image (no EXIF date).\n";
	return $image;
    }

    $date =~ s/[\s\.]/\-/sg;
    $date =~ s/://sg;

    my $ext = $image;
    $ext =~ s/^.*\.//g;
    $ext = 'tif' if $ext eq 'tiff';
    $ext = 'jpg' if $ext eq 'jpeg';

    my $newName = "$date.$ext";

    if (-f "$newName") {
        my $num = 0;
        do {
            $num++;
            $newName = "$date\-$num.$ext";
        } while (-e "$newName");
    }
    

    rename("$image", "$newName") unless $opt_n;
    print "Rename $image to $newName\n";

    return "$newName";
}
