#!/bin/bash

function die {
   echo "$1"
   echo "Usage: $0 TOPLEVELMFMDIRECTORY"
   exit 1
}

function lookfor {
    for b in "$@"; do
	found=$(which "$b" 2>/dev/null)
	if [ -n "$found" ]; then
	    if [ -x "$found" ]; then
		echo "$found"
		return
	    fi
	fi
    done
}

ffmpeg=$(lookfor avconv ffmpeg)
if [ -z "$ffmpeg" ]; then
    die "Can't find ffmpeg or avconv.  Perhaps 'sudo apt-get install libav-tools'?"
else
    echo "Will use '$ffmpeg' for encoding"
fi

todir=`readlink -m "$1"`
viddir=$todir/vid
if [ ! -d $viddir ] ; then
   die "'$viddir' is not a directory."
fi

outfile="$todir.mp4"
touch "$outfile" || die "Can't touch '$outfile'"
if [ ! -w "$outfile" ] ; then
    die "Can't write '$outfile'"
else
    rm -f "$outfile"
fi

linkdir=$todir/vlinks
if [ -d "$linkdir" ] ; then
    echo "Deleting old '$linkdir'"
    rm -rf "$linkdir" || die "Can't delete '$linkdir'"
fi

mkdir -p "$linkdir" || die "Can't create directory '$linkdir'"
echo -n "Creating sequential symlinks in '$linkdir'.."

x=1
for i in $viddir/*.png; do
    counter=$(printf %06d $x)
    ln -s "$i" $linkdir/img"$counter".png
    x=$(($x+1))
done
sync

echo "done. $x symlinks created."
echo
echo "BEGINNING HD VIDEO GENERATION TO $outfile.  THIS MAY TAKE A WHILE!"
echo

$ffmpeg -f image2 -r 30 -vf pad="1920:1080:(ow-iw)/2:(oh-ih)/2:0x0f0f0f" -i "$linkdir/img%06d.png" -vcodec libx264 -r 30 -pix_fmt yuv420p $outfile