#! /bin/bash

function usage() {

if [ $# -ne 1 ]; then
	echo "ExifDater - version 0.1 - March 23 2006"
	echo "El-Lotso <nikeow@yahoo.com>"
	echo "This  is  free  software;  see the source for copying conditions."
	echo "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR"
	echo "A PARTICULAR PURPOSE."
	echo
	echo "ExifDater utilises the exiftags( http://johnst.org/sw/exiftags/)"
	echo "program to sequentially extract the image creation date from"
	echo "JPEG EXIF headers."
	echo 
	echo "Usage:"
	echo "$0 /path/to/JPG/directory"
	exit 0
fi
}

function exiftimexist(){
which exiftime > /dev/null 2>&1
if [ $? -ne 0 ]; then
	echo
	echo "Unable to locate exiftime binary"
	echo "Please make sure it is installed and is in your path."
	echo
	exit 0
fi
}



function gotodir(){
cd $1 > /dev/null 2>&1

if [ $? -ne 0 ]; then
	echo
	echo "Directory does not exists"
	echo "Please try again."
	echo
	exit 0
fi

}

function JPGexist(){
find . -iname "*.JPG" -type f >/dev/null 2>&1

if [ $? -ne 0 ]; then
	echo
	echo "There are no JPEG pictures in this directory"
	echo "Please try again."
	echo
	exit 0
fi
}
	

function myexifdater(){
for i in *.JPG
do
	create_date=`exiftime "$i" 2>&1 | grep -i image\ created | cut -d" " -f3 | sed -e 's/:/-/g'`
	if [ "$create_date" == "" ]; then
		echo -e "SKIPPING IMAGE $i \\t\\t\\t [NO EXIF DATA FOUND]"
		continue
	fi
	echo -n Processing Image $i Created on $create_date
	do_rename=$( echo $i | sed -e 's/\(.*\)/mv "&" "'$create_date'_\1"/g'|sh)
	echo -e \\t\[DONE\]

done
}

usage $1
exiftimexist
gotodir $1
JPGexist
myexifdater
