#!/bin/bash
#
# converts an MKV file to PS3 format
#
# Requires avconv and HandbrakeCLI
#
# This script will attempt to convert a file with avconv (fast)
# and will fallback to Handbrake to encode more difficult files
# when encountering an error.
#

# Log start time
START_TIME=$(date +%s)

function mkvextensions() {
#filter out files that don't have mkv extensions and produce a list of files extension free
  if [ "${1:(-4)}" = ".mkv" ]; then
		filenamePath="${1:0:(-4)}"
	else	
		filenamePath=''
	fi
}

function removePath() {
	filenameOnly="${1##*/}"
}

for filename in $@
do
	mkvextensions $filename
	if [ "$filenamePath" != "" ]; then
		removePath $filenamePath
		echo "--- [$filenamePath.mkv] ---"
		avconv -i "$filenamePath.mkv" -c:v copy -c:a ac3 -b:a 448k "$filenameOnly.mp4"
		if [ "$?" != "0" ]; then
			echo "!!! Encode failed $filenameOnly.mp4 !!!"
			rm $filenameOnly.mp4
			echo "--- Switching to HANDBRAKE for $filenameOnly.mkv ---"
			HandBrakeCLI -i "$filenamePath.mkv" -o "$filenameOnly.mp4" -e x264  -q 20.0 -a 1 -E ffac3 -6 stereo -R Auto -D 0.0 --audio-copy-mask ac3,aac,mp3 --audio-fallback ffac3 -f mp4 --loose-anamorphic --modulus 2 -m --x264-preset veryfast --h264-profile main --h264-level 4.2
		fi
	fi	
done

#log end time
END_TIME=$(date +%s)
echo "Conversion time: $(( $END_TIME - $START_TIME )) seconds"