#!/bin/bash

# script designed to help unload photos from camera/cd/or_whatever
# to folders ordered by date based on EXIF info.
# USAGE:  cd /to/the/folder/where/the/files/are
#         sh photo-save.sh
# DEPENDS on: exiv2
# HINTS: if you have multiple cameras you can:
#       - copy this script accordingly: ex.  cp photo-save.sh photo-save-d50.sh
#       - make sure that UNLOAD parameter is set: ex. /home/user/unload/d50/
#       - now use photo-save-d50.sh instead of photo-save.sh
#       - repeat the same for as many cameras you need to..
#       if you didn't already know, you can chmod +x photo-save.sh and copy it
#       to a "bin" folder (ex /usr/local/bin/)
#
# AUTHOR: Emmanuel REVAH manu-AT-manurevah.com  http://manurevah.com/
# i'm not sure about a licence so whatever, just don't sue me.. . ... :]
# \o/

# root folder for unloading pictures to
UNLOAD='/home/manu/toph/unload/d50/'

# the script can either work on files in current directory OR
# work on files in current directory AND recursively
# 1=current ;  2=recursive
METHOD=2

if [ ${METHOD} == 1 ]; then
# Methode 1 options
# types of files we want to move/copy (space separated values)
# HINT: you might need to add uppercase extensions
EXTENSIONS="*.jpg *.nef"
# list files based on EXTENSIONS
FILETYPES=`ls ${EXTENSIONS} 2>/dev/null`
fi

if [ ${METHOD} == 2 ]; then
# Method 2 options
# you'll have to add the extensions accordingly
# default line (you can replace "name" by "iname" for removing case sensitivity)
# FILETYPES=`find . -name "*.jpg" -or -name "*.nef"`
FILETYPES=`find . -name "*.jpg" -or -name "*.nef"`
# avec regex: find ./ -regex ".*\(jpg\|nef\)$"
fi

# for every file we will find out the EXIF date and put the file into the
# apropriate dated folder (created if needed)
for i in ${FILETYPES}; do
        YEAR=`exiv2 $i 2>/dev/null |grep timestamp|cut -d " " -f 4|cut -c 1-4`
        MONTH=`exiv2 $i 2>/dev/null |grep timestamp|cut -d " " -f 4|cut -c 6,7`
        DAY=`exiv2 $i 2>/dev/null |grep timestamp|cut -d " " -f 4|cut -c 9,10`
        WHEREIGO=${UNLOAD}/${YEAR}/${MONTH}_${YEAR}/${DAY}_${MONTH}_${YEAR}

        # test if value year is empty
        if [ -z ${YEAR} ]
                then
                echo "$i: No Exif data found in the file"
                else
                mkdir -p ${WHEREIGO}
                cp $i ${WHEREIGO}
        fi;
done

exit
