#!/bin/bash
#
# This script will sort image by their creation date.
# The date value is extractet using metacam out of the
# image exif header.
# The folders will be named year-month-day
# usage: image-datesort.sh *.jpg
# by ckeller@informatik.uni-freiburg.de
#
# changed to be able to take jhead or metacam to
# get the date information from the exif-header.
# by jochen.eppler@gmx.de

if [ -z $1 ]; then
    echo "No files where given"
    exit 1
fi

JHEAD=`which jhead`
METACAM=`which metacam`
PROG=dummy

if [ -x $JHEAD ]; then
    PROG=$JHEAD
    GREP="Date/Time"
else if [ -x $METACAM ]; then
    PROG=$METACAM
    GREP="Image Capture Date:"
else
    echo "Neither jhead nor metacam has been found on your system!"
    echo "Install one of these tools."
    exit 2
fi
fi

fileext=$@

for file in `ls $fileext`
do

    echo "processing file '$file'"
    line=`$PROG $file | grep $GREP`

    year=`echo $line | cut -d: -f2 | cut -b2-5` 
    month=`echo $line | cut -d: -f3 | cut -b1-2`
    day=`echo $line | cut -d: -f4 | cut -b1-2`
  
    echo "found date: $year-$month-$day"

    [ -d "$year-$month-$day" ] || mkdir "$year-$month-$day";
  
    mv $file "$year-$month-$day"
done

exit 0
