#!/bin/bash
# (c) 2006 Simon Ruggier
#	This program is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 2 of the License, or
#	(at your option) any later version.
#
#	This program is distributed in the hope that it will be useful, but WITHOUT
#	ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#	FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
#	more details.
#
#	You should have received a copy of the GNU General Public License along with
#	this program; if not, write to the Free Software Foundation, Inc., 51
#	Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

# This script can be run from anywhere and will output a directory in the
# current folder full of flash files.  If the first argument is -t, it will also
# transcode them all using ffmpeg2theora as a bonus.

CURDIR=`pwd`;
OUTDIR="$CURDIR/CachedFlashFiles";
CMD=mv;

mkdir -p $OUTDIR;

i=1;
OUTFILE=$OUTDIR/"`printf %.3d $i`.flv";

# use every Cache directory we can find
for dir in ~/.mozilla/firefox/*/Cache/.; do
	cd $dir;
	for file in *; do
		# if the file is a flash video
		if echo "`file ${file}`"|grep "Macromedia Flash Video" > /dev/null; then
			# increment until we have  filename that won't overwrite an
			# existing video
			while [ -f "$OUTFILE" ]; do
				((++i));
				OUTFILE=$OUTDIR/"`printf %.3d $i`.flv";
			done;
			$CMD ${file} $OUTFILE;
		fi
	done
done

# if the first argument is -t
if [ "x-t" == "x$1" ]; then
	cd $OUTDIR;
	for file in $OUTDIR/*.flv; do
		# if the theora version of this file doesn't exist, create it
		if [ ! -f ${file%flv}ogg ]; then
			ffmpeg2theora "$file";
		fi
	done
fi

cd $CURDIR;