#!/bin/bash
#
# rename-vids: rename AVI movies as exported from Canon digital cameras
# by date (e.g. 2002/04/02/11-42-22.avi). It seems to work well with
# AVI movies exported by Canon Powershot G2 and S200 camera; ymmv.
#
# usage: rename-vids *.THM (preferred)
#    or: rename-vids *.AVI
#
# source: http://impressive.net/people/gerald/2002/04/rename-vids
#
# if environment variable W is defined, uses that as base dir;
# otherwise, uses current dir.
#
# Gerald Oskoboiny, 2 Apr 2002
#
# $Id: rename-vids,v 1.12 2009/07/05 23:25:58 gerald Exp $
#

if [ -z $W ]; then
    target=.
else
    target=$W
fi

cwd=$PWD
for vid in $@; do
    echo "$vid" | grep -q -i thm$
    if [ $? -eq 0 ]; then
	cd $target
	ymdhms=$(epinfo -rf '%Y/%m/%d/%H-%M-%S.thm' $cwd/$vid | \
	    grep ^rename | sed 's/.* //; s/\.thm$//' )
	cd - > /dev/null
	vid=$(echo $vid | sed 's/THM$/AVI/; s/thm$/avi/')
    else
	ymdhms=$(date "+%Y/%m/%d/%H-%M-%S" \
	    --date "$(strings $vid | egrep '^.{17}[0-9]{2} [0-9]{4}$' | head -1) UTC")
    fi
    if [ -z $ymdhms ]; then
	echo "unable to find a date for $vid; skipping it"
	continue
    fi
    d=$(dirname $ymdhms)
    if [ ! -d $target/$d ]; then
	mkdir -v -p $target/$d
    fi
    mv -i -v $vid $target/$ymdhms.avi
done

# seems fixed in ubuntu etch (or earlier)
# echo >&2
# echo 'NOTE: filenames may be off by an hour due to epinfo bug!' >&2
# echo >&2

#
# changelog:
#
# $Log: rename-vids,v $
# Revision 1.12  2009/07/05 23:25:58  gerald
# handle videos from olympus stylus tough 8000 with multiple date entries
#
# Revision 1.11  2008-07-06 04:30:28  gerald
# bug fixes (not sure how it could have worked with the previous rev)
#
# Revision 1.10  2004/01/10 05:04:11  gerald
# added a pointer to source code
#
# Revision 1.9  2004/01/10 05:03:12  gerald
# get date/time info from .thm files if they exist;
# made strings output parsing a bit stricter
#
# Revision 1.8  2003/02/03 05:47:38  gerald
# made date extraction more robust (forgot to ^-anchor the regexp)
#
# Revision 1.7  2002/08/08 03:46:17  gerald
# updated intro text to note that it works with Canon S200's as well as G2's
#
# Revision 1.6  2002/05/17 06:47:29  gerald
# added -i to mv to avoid clobbering files
#
# Revision 1.5  2002/05/17 06:44:44  gerald
# made extracting dates from vids a bit more robust
#
#

