#!/bin/sh

# iphotocleanup.sh
# Quick and dirty script by Stephanie Troeth
#
# Description: 
# This script may help you if you have different versions of iPhoto 
# Libraries and want to consolidate them. iPhoto doesn't know how to 
# do it cleanly, so we have to do some cleaning up on the iPhoto Library
# you wish to import.
# 
# You need to download two files before you can use the second part
# of this script. These files are:
# http://home.cfl.rr.com/genecash/digital_camera/EXIF.py
# http://home.cfl.rr.com/genecash/digital_camera/exiftool
# I have put them in a directory called 'bin' in my home directory.
# If you choose to put them elsewhere, make sure the python command
# below calls 'exiftool' from the right place.
# 
# Questions, suggestions, complaints to steph@unadorned.org
###

# We expect one argument only

if [ $# != 1 ]; then
	echo ""
	echo "Usage: iphotocleanup.sh <root-dir>" 
	echo ""
	echo "This program:-"
	echo "  * remove all "Thumbs" in subdirectories in <root-dir>"
	echo "  * ensures that your photo files have the last modified time of when they were taken (according to EXIF DateTimeOriginal)"
	exit 1	
fi


rootdir=$1

# First you have to remove all the Thumbs directories so that
# iPhoto wouldn't duplicate all your pictures

thumblist=`find $1 -name 'Thumbs'`

for dir in $thumblist
do
	if [  -d $dir  ];  then 
		echo "Removing $dir"
		rm -rf $dir	
	fi
done

# Here we find all the photo files and changed the last modified date according
# to the relevant EXIF information in each photo file.
#
# I've put in a filter for DCP*.JPG or IMG*.JPG because my photos are named 
# that way by my cameras. You might have to change this bit to whatever suits 
# your file.

list=`find $1 -iname "[DCP|IMG]*.JPG" -print`

for file in $list
{
	echo "Touching $file"

	datetime=`python ~/bin/exiftool -v $file | grep 'DateTimeOriginal' | awk '{ print $3 $4 }' | sed 's/://g; s/\([0-9][0-9]\)$/\.\1/'`

	touch -t $datetime $file
}

