#!/bin/bash 

extension=CR2
FOLDER=/home/sebschub/Dokumente/Bilder/RAW


extensionLC=`echo $extension | tr "[:upper:]" "[:lower:]"`

echo Getting RAW files from camera

mkdir $FOLDER/temp
cd $FOLDER/temp

echo Temporary saving to $FOLDER/temp

gphoto2 --get-all-raw-data

for i in *.$extension; do
    # Datum fuer Dateinamen
    date_stamp=`exiftool -DateTimeOriginal -d "%Y%m%d-%H%M%S" $i`
    yyyymmdd_hhmmss=$(expr substr "`echo $date_stamp`" 22 36)

    # Datum fuer Verzeichnisse mit Bindestrichen
    date_stamp=`exiftool -DateTimeOriginal -d "%Y-%m-%d" $i`
    yyyymmdd=$(expr substr "`echo $date_stamp`" 22 32)
    yyyymm=$(expr substr "`echo $yyyymmdd$`" 1 7)

    mkdir -p ../$yyyymm/$yyyymmdd

    unique_num=1
    i_renamed="../$yyyymm/$yyyymmdd/$yyyymmdd_hhmmss-`printf "%02i" $unique_num`.$extensionLC"
    while [ -e $i_renamed ]; do
	unique_num=$[$unique_num+1]
	i_renamed="../$yyyymm/$yyyymmdd/$yyyymmdd_hhmmss-`printf "%02i" $unique_num`.$extensionLC"
    done
    mv $i $i_renamed
    echo "$i -> $i_renamed"
done

cd ..

rmdir $FOLDER/temp
echo Removing temporary folder $FOLDER/temp

echo FINISHED