#!/bin/sh
# This Bourne shell script for GNOME invokes exifiron on all
# JPEG images on a removable media, to copy them into a new directory.
# It also copies MJPEG AVI files and thumbnails produced by some Canon cameras.
# It also copies raw image files produced by some Canon cameras.

# This script is in the public domain.  marko.makela (at) iki.fi, May 1, 2003.
# Last revision: November 19, 2006.

# treat all errors as fatal
set -eu

# mount point
MNT="`hal-get-property --udi "$1" --key volume.mount_point`"
# exifiron program name
EXIFIRON=exifiron
# output directory name
DIR="$HOME"/"`date +"%Y/%m/%d %H:%M:%S"`"
# uncomment the following line if your camera is in Universal Coordinated Time.
#TZ=UTC0;export TZ

# Directory names and file name suffixes.
# These can be in upper or lower case, depending on the mount options.
dcim="DCIM"
jpg="JPG"
avi="AVI"
thm="THM"
cr2="CR2"

# helper function for checking if a glob pattern matches any files
# (since the nullglob option is not available in all Bourne shells)
glob_exists () {
    [ -f "$1" ]
}

iron () {
    if glob_exists "$@"
    then
	mkdir -p "$DIR"
	"$EXIFIRON" -E -s "$DIR" "$@"
    fi
}

# copy all JPEG images
iron "$MNT"/$dcim/*/*.$jpg

# copy all movie thumbnail files
iron "$MNT"/$dcim/*/*.$thm
# copy the movie files (MJPEG on Canon cameras) for each thumbnail file
if glob_exists "$DIR/*.$thm"
then
    for i in "$DIR"/*.$thm
    do
	BASE="`expr "$i" : ".*/\(.*\)\.$thm"`"
	cp "$MNT"/$dcim/*/"$BASE".$avi "$DIR"
	touch -cr "$i" "$BASE".$avi
    done
fi

# copy all raw images
if glob_exists "$MNT"/$dcim/*/*.$cr2
then
    mkdir -p "$DIR"
    cp -p "$MNT"/$dcim/*/*.$cr2 "$DIR"
    for i in "$DIR"/*.$cr2
    do
	BASE="`expr "$i" : ".*/\(.*\)\.$cr2"`"
	if [ -e "$BASE".$jpg ]; then
	    touch -cr "$BASE".$jpg "$i"
	fi
    done
fi

if [ -d "$DIR" ]
then
    nautilus "$DIR"
fi
