#!/bin/sh

# main loop
find . -type f \
       -maxdepth 1 \
       \( -iname "*.cr2" \
          -o -iname "*.dng" \
          -o -iname "*.tif" \
          -o -iname "*.orf" \) \
       -exec basename "{}" \; | sort | \
while read file
do

    ext=${file##*.}
    printf "%s [" "${file}"

    # try some exif values to gather date/time
    EXIF="$(exiftool -createdate -d %Y-%m-%d_%H-%M-%S -T "${file}")"

    # handle invalid dates
    if [ "$EXIF" = "0000:00:00 00:00:00" ]
    then
        EXIF="$(exiftool -datetimeoriginal -d %Y-%m-%d_%H-%M-%S -T "${file}")"
    fi
    if [ "$EXIF" = "0000:00:00 00:00:00" ]
    then
        EXIF="$(exiftool -datetimeutc -d %Y-%m-%d_%H-%M-%S -T "${file}")"
        if [ "$EXIF" != "0000:00:00 00:00:00" ]
        then
            EXIF=$(date -f %s -j "$(( $(date -f "%Y-%m-%d_%H-%M-%S" -j "$EXIF" +%s) + 3600 ))" +"%Y-%m-%d_%H-%M-%S")
        fi
    fi

    # skip if there is no (proper) exif data
    if [ -z "$EXIF" ] || [ "$EXIF" = "0000:00:00 00:00:00" ]
    then
        printf " no exif data ]\n"
        continue
    fi

    for variant in a b c d e f g h i j k l m n o p q r s t u v w x y z
    do
       # same file? then we've converted it already.
       if [ "${file}" = "${EXIF}-${variant}.$ext" ]
       then
           printf " %s->found" "$variant"
           break
       fi

       # variant is is already existing - try next one
       if [ -f "${EXIF}-${variant}.$ext" ]
       then
           continue
       fi

       # rename file
       printf " %s->rename" "$variant"
       mv "${file}" "${EXIF}-${variant}.$ext"

       # check for matching jpg files
       for type in jpeg JPEG jpg JPG xmp XMP psd PSD
       do
          if [ -f "${file%.*}.$type" ]
          then
              printf " + $type"
              mv "${file%.*}.$type" "${EXIF}-${variant}.$type"
          elif [ -f "${file}.$type" ]
          then
              printf " + $type"
              mv "${file}.$type" "${EXIF}-${variant}.$type"
          fi
          case $type in
              [xX][mM][pP])
                  if [ -f "${EXIF}-${variant}.$type" ]
                  then
                      sed -i "s,\(crs:RawFileName=\"\).*[^\"]\",\1${EXIF}-${variant}.$ext\",g" "${EXIF}-${variant}.$type";
                      sed -i "s,\(xmpMM:DerivedFrom=\"\).*[^\"]\",\1${EXIF}-${variant}.$ext\",g" "${EXIF}-${variant}.$type";
                  fi
              ;;
          esac
       done

       # we're done here
       break
    done
    printf " ]\n"
done
