#!/bin/sh

# To use this script:
# In gnome-volume-properties, for the Digital Camera command, put this:
#  /path/to/script/import-photos %h

# Options: __________________________________________________________

# After copying the pictures, prompt to browse them with this program
BROWSE_PROG="gthumb";

# Starting directory for "select destination directory" dialog
DEFAULT_DEST="/home/steve/Desktop/photos/working/";

# ___________________________________________________________________


#######################################################################
# Don't modify anything below this unless you know what you're doing. #
#######################################################################

# hal stuff from /usr/bin/gnome-volume-manager-gthumb...
MOUNT_POINT=$(hal-get-property --udi "$1" --key volume.mount_point)
if test -z "$MOUNT_POINT"; then
  gthumb --import-photos
  exit 0
fi

ROOT=${MOUNT_POINT}
dcim=$(ls "${ROOT}" | grep -i dcim)
if [ $? -eq 0 ]; then
    ROOT="${ROOT}/$dcim"
    # if there is only one dir in the dcim directory, enter it
    if test $(/bin/ls -1 "${ROOT}" | wc -l)  -eq 1; then
	ROOT="${ROOT}/$(ls -1 "${ROOT}" | head -n 1)"
    fi
fi

PICS_DEST=$DEFAULT_DEST;

PICS_DEST=`zenity --file-selection --directory --filename="$DEFAULT_DEST" --title="Import Photos: Select Destination Directory"`;
if [ -ne $PICS_DEST ] ; then exit 1; fi

PICS_SRC=$ROOT;

FILES=`find $PICS_SRC -type f -iregex '\(.*\.jpg\|.*\.avi\|.*\.mov\|.*\.mpg\)'`

NUM_FILES=`echo "$FILES" | wc -l`

function copy_pictures ()
{
    (
	CURRENT="1"
	echo -e "$FILES" | while read line ; do
	    PER=`echo $CURRENT/$NUM_FILES*100 | bc -l`
	    echo $PER
	    echo "# File $CURRENT of $NUM_FILES : $line"
	    cp "$line" "$PICS_DEST"
	    CURRENT=$[CURRENT+1]
	done
	echo 100
    ) |
    zenity --progress \
	--title="Copying Files..." \
	--text="current file" \
	--percentage=0

    # Note: Cancel actually seems to crash quietly... :|
    if [ "$?" != 0 ] ; then
        zenity --error \
            --text="Copying cancelled.";
    fi
}

copy_pictures;

# Ask if user would like to open destination folder with browser
zenity --question --title="Browse copied pictures?" \
    --text="Would you like open the destination directory with '$BROWSE_PROG'?";

if [ "$?" = 0 ] ; then
    # Browse
    `"$BROWSE_PROG" "$PICS_DEST"`;
else
    # Add notification that process is complete
    zenity --notification --window-icon="info" \
	--text="Import Photos: $NUM_FILES files copied to '$PICS_DEST'"&
fi

exit 0;
