#!/usr/bin/perl
# $Id: rename2date.pl,v 1.2 2004/07/13 20:12:27 kgarner Exp $
#
# This program renames a file to the date it was created, trying to preserve
# the extention.

use strict;
use vars qw/$ARGC $opt_i $opt_c $opt_d $opt_v/;

use File::Basename;
use File::Copy;
use Image::Info qw(image_info);
use Getopt::Std;

sub usage {
    printf("rename2date.pl [options] <file> <file> <file>\n");
    printf("    -c <dir>  Don't rename in place," .
           "but actually copy to this directory\n");
    printf("    -d        Don't actually do the renaming\n");
    printf("    -i        Use DateTime field in EXIF data in jpeg.\n");
    printf("    -v        Be verbose\n");
}

# extention borrowed from the Perl Cookbook
sub extension {
    my $path = shift;
    my $ext = (fileparse($path, '\..*?'))[2];
    $ext =~ s/^\.//;
    return $ext;
}

getopts('c:div');

$ARGC = @ARGV;

if ($ARGC <= 0) {
    &usage();
}

foreach my $i (@ARGV) {
    my $fileTime = (stat($i))[9];
	
    my $ext = &extension($i);
    (my $basename, my $dirname) = fileparse($i);

    if ($dirname eq "./") {
        undef $dirname;
    }

    my $seconds, my $minutes, my $hour, my $day, my $month, my $year;
    if ($opt_i)
    {
        my $info = image_info($i);
        my $dateTime = $info->{"DateTime"};
        if ($dateTime =~ /(\d+):(\d+):(\d+) (\d+):(\d+):(\d+)/)
        {
            $year = $1;
            $month = $2;
            $day = $3;
            $hour = $4;
            $minutes = $5;
            $seconds = $6;
        }
    }
    else
    {
        ($seconds, $minutes, $hour, $day, $month, $year) =
            (localtime($fileTime))[0,1,2,3,4,5];
        $year += 1900;
        $month += 1;
    }

    if ($opt_c)
    {
        $dirname = $opt_c;
        if (!($dirname =~ /\/$/))
        {
            $dirname = $dirname . "/";
        }
    }

    my $newname = sprintf("%s%4d_%02d_%02d-%02d_%02d_%02d.%s", $dirname,
                          $year, $month, $day, $hour, $minutes,
                          $seconds, $ext);

    if ($opt_v) {
        printf("renaming %s to %s\n", $i, $newname);
    }

    if (!$opt_d) {
        if ($opt_c)
        {
            copy($i, $newname);
        }
        else
        {
            rename ($i, $newname) or warn "Couldn't rename file: $!";
        }
    }
}
