#!/bin/sh

masterlib="/Volumes/iTunes/iTunes/iTunes Media/TV Shows/"
handbrake="/Volumes/Data/HandBrakeCLI"
hbopts="-e x264  -q 20.0 -a 1 -E faac -B 128 -6 dpl2 -R Auto -D 0.0 -f mp4 -X 480 -m -x cabac=0:ref=2:me=umh:bframes=0:weightp=0:subme=6:8x8dct=0:trellis=0"

find "${masterlib}" -type f -print0 | while read -d $'\0' curfile; do
	relativepath=`echo $curfile | sed -e "s,${masterlib},,"`;
	isnetatalk=`echo ${curfile} | grep -c "AppleDouble"`;
	if [ "$isnetatalk" -ne "0" ]; then
		continue;
	fi
	if [ ! -f "iTunes Media/TV Shows/${relativepath}" ]; then
		truncname=`echo ${relativepath} | sed -e 's/ (HD)//g' | sed -e 's/ (SD)//g' | sed -e 's/ (DVD)//g'`
		#echo "Checking iTunes Media/TV Shows/${truncname}"
		if [ ! -f "iTunes Media/TV Shows/${truncname}" ]; then
			truncname=`echo ${relativepath} | sed -e 's/ (1080p HD)//g' | sed -e 's/ (1080p)//g'`
			#echo "Checking iTunes Media/TV Shows/${truncname}"
			if [ ! -f "iTunes Media/TV Shows/${truncname}" ]; then
				echo "Missing iTunes Media/TV Shows/${relativepath}";
		
				if [ ! -f "needsync/TV Shows/$relativepath" ]; then
					relativedir=`dirname "$relativepath"`
					echo "Would create needsync/TV Shows/$relativepath";
					mkdir -p "needsync/TV Shows/$relativedir"
					${handbrake} ${hbopts} -i "$curfile" -o "needsync/TV Shows/$relativepath" < /dev/null
				else
					echo "Created but needs syncing: needsync/TV Shows/$relativepath";
				fi
			else
				if [ -f "needsync/TV Shows/$relativepath" ]; then
					echo "Unnecessary needsync file: needsync/TV Shows/$relativepath";
					rm -f "needsync/TV Shows/$relativepath";
				fi
			fi
		else
			if [ -f "needsync/TV Shows/$relativepath" ]; then
				echo "Unnecessary needsync file: needsync/TV Shows/$relativepath";
				rm -f "needsync/TV Shows/$relativepath";
			fi
		fi
	else
		if [ -f "needsync/TV Shows/$relativepath" ]; then
			echo "Unnecessary needsync file: needsync/TV Shows/$relativepath";
			rm -f "needsync/TV Shows/$relativepath";
		fi
	fi
done
