#!/bin/bash

#
# This script compiles all the images captured from fswebcam and creates a link tree, plus 
# starts the ffmpeg encoder.
#

set -e

WORKDIR=~/links/
SOURCEDIR=/media/8064-50CA/
INDEXFILE=/tmp/makelinks.txt

echo "*** Using ${WORKDIR} for link tree."
cd ${WORKDIR}

echo "*** Using ${SOURCEDIR} to find all .jpg files, indexing to $INDEXFILE"
echo > $INDEXFILE

for i in `find ${SOURCEDIR} -type f -name '*.jpg'`
do
	f=$i
	b=`basename $f`
	echo $b $f >> $INDEXFILE
	echo -ne "*** Processing $f ...\r"
done
echo "*** Done."

echo "*** Sorting source list, and generating new link tree."
counter=1

# INDEXFILE contains a big list of files - the first field is the raw filename,
# the second is the path to the file.  Sort it so we get it in the right order, then
# pluck off the path, making the link tree...

sort ${INDEXFILE} | while read -r index source
do
	if [ -z $source ] 
	then
		continue
	fi
	printf -v linkname "frame-%05d.jpg" $counter
	echo -ne "*** Linking frame $linkname to $source ...\r"
	ln -s $source ${WORKDIR}/${linkname}
	counter=`expr $counter + 1`
done

echo "" 

echo "*** Encoding $counter frames of video at 30..."
ffmpeg -f image2 -y -i ${WORKDIR}/frame-%05d.jpg -r 30 -s 640x480 -vcodec libx264 -vpre hq -vb 500000 output.mp4

echo "Done."

