#!/bin/bash
# This script mergs GPS data from xmp files created by the taggr software
# into Canon's RAW (.CR2) files that will be imported by Apple Aperture 3
# Copyright (c) by Niels Fallenbeck
#
# This script requires exiftool which can be downloaded from
# http://www.sno.phy.queensu.ca/~phil/exiftool/
echo "GPS Converter Script 1.0 using exiftool"
echo "2010 by Niels Fallenbeck <niels@fallenbeck.com>, http://www.fallenbeck.com"

#############################################################################
# Do some checks

if [ $# -ne 1 ]; then
	echo "You have to specify the directory in which the .xmp files are stored."
	echo "This is the directory which you specified as \"Destination folder\""
	echo "in the Taggr software."
	echo ""
	echo "   usage: `basename $0` <working dir>"
	echo "     e.g. `basename $0` /Users/fallenbeck/Desktop/NeueFotos"
	exit 1
fi

WORKINGDIR=$1

if [ ! -d "${WORKINGDIR}" ]; then
	echo "\"${WORKINGDIR}\" is not a directory. Abort."
	echo "Make sure that you specify the directory in which the .CR2 files"
	echo "and the .xmp sidecar files reside."
	echo ""
	echo "   usage: `basename $0` <working dir>"
	echo "     e.g. `basename $0` /Users/fallenbeck/Desktop/NeueFotos"
	exit 2
fi

EXIFTOOL=`which exiftool`

if [ ! -x ${EXIFTOOL} ]; then
	echo "Binary \"${EXIFTOOL}\" is not executable. Abort."
	echo "Please download the exiftool software from"
	echo "   http://www.sno.phy.queensu.ca/~phil/exiftool/"
	echo ""
	echo "After that install the software and make sure that the exiftool"
	echo "binary is in your path."
	exit 3
fi

#############################################################################
SOURCEEXT=".xmp"
TARGETEXT=".CR2"

# Change directory
MYDIR=`pwd`
cd "${WORKINGDIR}"

# convert all files you can find
for filename in `ls -1 *${SOURCEEXT}`; do
	# build the filenames
	fname=`basename ${filename} ${SOURCEEXT}`
	s=${fname}${SOURCEEXT}
	t=${fname}${TARGETEXT}

	echo "   Merging ${s} -> ${t}"
	
	# convert
	${EXIFTOOL} -overwrite_original -preserve -tagsFromFile ${s} ${t}
done

# return to old directory
cd "${MYDIR}"
