#!/bin/bash +e

#if no directory is given, then apply only to the current directory.
if [ -z "$1" ] 
then
	echo ""
	echo "Searches for .xmp-files that do not have a corresponding .NEF- .jpg- .JPG- or .jpeg-file"
	echo "and deletes those 'unused' .xmp-files"
	echo ""
	echo "Usage: 'delete-xmp-files dir [dir ...]'"
	echo "e.g. : 'delete-xmp-files .' to apply for this directory"
	echo "       'delete-xmp-files dir1 dir2 dir3' to apply to multiple directories"
	echo "       'delete-xmp-files dir*' to apply to all directories that match 'dir*'"
	echo ""
	exit 0
else
	Directories=$*
fi

# init a counter
count=0

#go through all directories
for NextDir in $Directories ; do
	echo ""
	echo "looking for: $NextDir/DSC_*.xmp'"
	XmpInCurrentDir="$NextDir/DSC_*.xmp"

	#go through all xmp files
	for NextXmp in  $XmpInCurrentDir; do

		# get the name for the nef- or jpg-file
		NefFile=${NextXmp/"xmp"/"NEF"}
		JPGFile=${NextXmp/"xmp"/"JPG"}
		JpegFile=${NextXmp/"xmp"/"jpeg"}
		JpgFile=${NextXmp/"xmp"/"jpg"}

		# check if NefFile or JpgFile for NextXmp exists
		if [[ -e $NextXmp && ! -e $NefFile && ! -e $JPGFile && ! -e $JpegFile && ! -e $JpgFile ]]
		then
			# delete the xmp if no NEF exists.
			#rm "$NextXmp"
			echo "$NextXmp deleted."
			count=$((count+1))
		fi	
	done
done

echo ""
echo "$count xmp-files deleted".

