#!/bin/bash

repertoire=$1
nomsortie=$2

# Lancement de l'outil d'ImageMagick
traite_exif ()
{
	exif=`identify -verbose -quiet "$i" 2>> /dev/null | grep 'xif:DateTime:' | tr -d ' '`
	if test "$exif" = "";then continue;fi
	annee=`echo $exif | cut -d ':' -f3`
	mois=`echo $exif | cut -d ':' -f4`
	jour=`echo $exif | cut -d ':' -f5 | cut -c1-2`
	heure=`echo $exif | cut -d ':' -f5 | cut -c3-4`
	minute=`echo $exif | cut -d ':' -f6`
	seconde=`echo $exif | cut -d ':' -f7`
	date_complete=`printf '%s_%s_%s_%sh%sm%s_%s.jpg' $annee $mois $jour $heure $minute $seconde "$nomsortie"`
	echo "${date_complete}"
	cp $i $repertoire/$nomsortie/$date_complete
}

# On verifie qu'un repertoire a ete entre
if test "$repertoire" = ""
then
	echo "Veuillez preciser le repertoire de photos a traiter !"
	exit 1
fi

# On verifie qu'un nom a ete entre
if test "$nomsortie" = ""
then
	echo "Veuillez preciser un nom de fichier generique a donner a vos photos !"
	exit 2
fi

# On verifie que le programme identify existe
which identify >> /dev/null 2>> /dev/null
identify_exists=`echo $?`
if test $identify_exists -ne 0
then
	echo "Veuillez installer ImageMagick !"
	exit 1
fi

mkdir $repertoire/$nomsortie

ls -b1 $repertoire/* | while read i
do
	nb_char=`echo -n "$i" | wc -c`
	prem_char=`expr $nb_char - 3`
	extension=`echo "$i" | cut -c${prem_char}-${nb_char} | tr a-z A-Z`
	if test "JPEG" = "$extension" || test ".JPG" = "$extension"
	then
		traite_exif "$i"
	fi
done