#!/bin/sh
# exif-chronological-rename.sh
# Written bu Daniel Foote, Nov 2004.
# Do as you will with this script.

# Version 1.1
# Fixes: inferior globbing fixed, refers to appropriate EXIF tags by
#        hex numbers instead of text.

# This script renames a set of jpeg files into chronological order,
# using their EXIF tags.

if [ "$1" = "" ]; then
	echo "Usage: $0 file-prefix"
	echo "  Where file-prefix is the prefix for the new files."
	echo "  Files are numbered from 0001 upwards."
	echo "  The files are moved into a subdirectory called Done"
	echo "    to allow the same prefix to be used again."
	exit
fi

# Get the fileprefix from the command line.
fileprefix="$1"
count=1

# Firstly, extract the date and time, and also keep the filename with it.
# The output of this loop is a list of the files in correct chronological order.
echo "Building list of files and sorting..."
for file in *.[Jj][Pp][Gg]
do
	filedate=`exif -t 0x0132 $file | grep Value | sed -e 's/\ \ Value:\ //g'`
	echo -n $filedate
	echo -n " "
	echo $file
done | sort | cut -d\  -f3 > Old-Sorted-Files.txt

# Get the list of old files.
oldfiles=`cat Old-Sorted-Files.txt`

# Now, give the files their new names.
# Files are moved to a "Done" subdir, to prevent
# name clashes if we use the same prefix.
echo "Renaming files..."
mkdir "Done"
for move in $oldfiles
do
	newname=`echo -n $fileprefix``printf "%04d" $count``echo -n ".jpg"`
	#echo $newname
	#echo $move

	mv "$move" "Done/$newname"

	let count=$count+1
done

echo "Process completed. Cleaning up."

# Clean up, and we're done.
rm -f Old-Sorted-Files.txt

