#!/bin/bash

# Reads EXIF creation date from all .JPG files in the
# current direcotry and moves them carefully under
#
#   $BASEDIR/YYYY/YYYY-MM/YYYY-MM-DD/
#
# ...where 'carefully' means that it does not overwrite
# differing files if they already exist and will not delete
# the original file if copying fails for some reason.
#
# It DOES overwrite identical files in the destination directory
# with the ones in current, however.
#
# The script depends on the 'metacam' package.
#
# site:http://elonen.iki.fi/code/misc-notes/digiphoto-archive-script/
#
# This script was originally written and put into
# Public Domain by Jarno Elonen <elonen@iki.fi> in June 2003.
# Feel free to do whatever you like with it.

  BASEDIR=/home/jarno/gfx

find -maxdepth 1 -name "*.JPG" | while read x; do
  DATE=`metacam "$x" | \
    egrep "^[ \t]*Image Capture Date:" | \
    sed -r "s/Image Capture Date: ([0-9:]*).*/\1/"`
  if [ ! -z "$DATE" ];
  then
    YEAR=`echo $DATE | sed -r "s/([0-9]*):([0-9]*):([0-9]*)/\\1/"`
    MONTH=`echo $DATE | sed -r "s/([0-9]*):([0-9]*):([0-9]*)/\\2/"`
    DAY=`echo $DATE | sed -r "s/([0-9]*):([0-9]*):([0-9]*)/\\3/"`
    if [ "$YEAR" -gt 0 ] & [ "$MONTH" -gt 0 ] & [ "$DAY" -gt 0 ]
    then
      INSTDIR=${BASEDIR}/${YEAR}/${YEAR}-${MONTH}/${YEAR}-${MONTH}-${DAY}
      install -d "$INSTDIR"
      INSTFILE="$INSTDIR/$x"
      if [ -e "$INSTFILE" ] && ! cmp -s "$x" "$INSTFILE"
      then
        echo "WARNING: '$INSTFILE' exists already and is different from '$x'."
      else
        echo "Moving '$x'"
        cp "$x" "$INSTFILE"
        if ! cmp -s "$x" "$INSTFILE"
        then
          echo "WARNING: copying failed somehow, will not delete original '$x'"
        else
          rm -f "$x"
        fi
      fi
    else
      echo "WARNING: '$x' doesn't contain date."
    fi
  else
    echo "WARNING: '$x' doesn't contain date."
  fi
done
