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

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

# treat all errors as fatal
set -eu

# 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" ]

# output directory name
DIR="`date +"%Y-%m-%d %H:%M:%S"`"
# uncomment the following line if your camera is in Universal Coordinated Time.
#TZ=UTC0;export TZ

# the mount point in /etc/fstab
MNT="/media/flash";
# sample /etc/fstab entry:
#/dev/hde1	/media/flash	vfat	defaults,user,noauto,noexec 0 0

DEV="`grep "	$MNT	" /etc/fstab | cut -f1`"
if [ -z "$DEV" ]
then
    echo "$MNT does not exist in /etc/fstab!" >&2
    exit 1
fi

# In devfs (of Linux 2.4) and udev (of Linux 2.6),
# the /dev tree is dynamically updated.
if [ ! -e "$DEV" ]
then
    echo -n "waiting for the CompactFlash card to be plugged in" >&2
    while [ ! -e "$DEV" ]
    do
	echo -n "." >&2
	sleep 1
    done
    echo
fi

mount "$MNT"

# copy all JPEG images
if glob_exists "$MNT"/dcim/*/*.jpg
then
    exifiron -s "$DIR" "$MNT"/dcim/*/*.jpg
fi

# copy all movie thumbnail images
if glob_exists "$MNT"/dcim/*/*.thm
then
    exifiron -s "$DIR" "$MNT"/dcim/*/*.thm
    # copy the movie files (MJPEG on Canon cameras) for each thumbnail file
    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
    cp -p "$MNT"/dcim/*/*.cr2 "$DIR"
fi

umount "$MNT"
#/sbin/cardctl eject
