#!/bin/bash

## Set this to the location that you extracted these scripts to
PROCESSINGDIRECTORY="/Volumes/Mac Pro Storage"
#Set this to the location you want your envoded movies to be saved to
ENCODEDDIRECTORY="/Volumes/Mac Pro Storage/3-Completed Encodes" ## This is the location that the finished video will be moved to after the encode finishes
RIPDIRECTORY="/Volumes/Mac Pro Storage"
RIPFAILED="/Volumes/Mac Pro Storage/0-Rip Failed"
EXTERNALSTORAGE1="/Volumes/Mac Pro Storage/3-Completed Originals"
EXTERNALSTORAGE2="/Volumes/Back-Up Originals"
###################################################################################
##  Don't muck with the rest of this script, you've already got it set up if     ##
##  you set the two previous variables                                           ##
###################################################################################

######################################################################################################################################################################
######################################################################################################################################################################
######################################################################################################################################################################

## You don't need to modify any of the following!!!
PATHTOHANDBRAKECLI="$PROCESSINGDIRECTORY/0-Applications"
READYDVDS="$PROCESSINGDIRECTORY/1-Raw" ## This is the directory where MacTheRipper is set to save movies to (you can also move finished rips from other sources here *Cough*torrents*Cough*)
INPROGRESS="$PROCESSINGDIRECTORY/2-Encoding" ## This is the location that video will be saved to while processing
COMPLETEDDVDS="$PROCESSINGDIRECTORY/3-Completed Originals" ## This is the directory where finished DVDs will be stored after they have been encoded
#Check if this script is already running (make sure we don't have multiple encodes running simultaniously)
if [ -e "$RIPDIRECTORY/ProcessingVideo.flag" ]
then
  echo Encode in process!
  exit
else touch "$RIPDIRECTORY/ProcessingVideo.flag"
fi

VERSION="0.4"
###################################################################################
##  Written by T3RC                                                              ##
##  May 2008                                                                     ##
##    encodes using hard coded settings (these are my own, they take a lot of    ##
##    processing time, but result in DVD quality audio/video at about 1/3 the    ##
##    size)                                                                      ##
##                                                                               ##
##  This script requires HandBrakeCLI 0.9.2+ to support of my encoding preset    ##
###################################################################################

echo "################################################################################"
echo ""
echo "           _______  ________ ______    ______  _       "
echo "          (_______)(_______/(_____ \  / _____)( )      "
echo "           _          ____   _____) )| /      |/   ___ "
echo "          | |        (___ \ (_____ ( | |          /___)"
echo "          | |_____  _____) )      | || \_____    |___ |"
echo "           \______)(______/       |_| \______)   (___/ "
echo "                                                                 "
echo "                     ______   _          _  _  _                     "
echo "                    (_____ \ (_)        | || || |                    "
echo "                     _____) ) _  ____   | || || |  ____  ____  ____  "
echo "                    (_____ ( | ||  _ \  | ||_|| | / ___)/ _  ||  _ \ "
echo "                          | || || | | | | |___| || |   ( ( | || | | |"
echo "                          |_||_|| ||_/   \______||_|    \_||_|| ||_/   $VERSION"
echo "                                |_|                           |_|    "
echo ""
echo "################################################################################"
echo ""

OLDIFS=$IFS
IFS=$'\n'

cd "$READYDVDS"

for SOURCE in $(find * -maxdepth 0 -print); do
	echo "$SOURCE"
   DESTINATION="$INPROGRESS/$SOURCE.m4v"
   echo "$DESTINATION" > "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt"
   DESTINATIONITOUCH=$(((grep "$DESTINATION" "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt" ) | sed s/"SDAppleTV"/"iTouch"/g ) | sed s/"HDAppleTV"/"iTouch"/g )
   echo Ripping DVD "$SOURCE" to "$DESTINATION"
   sleep 1
   echo "Begining encode..."

#Use Script to determine the Encode Settings
	FILENAME=$((basename "$SOURCE" ) | sed s/" - "/";"/g )
	echo "$FILENAME" > "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt"
	ENCODE=$(((((((grep "$FILENAME" "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt" ) | cut -d \; -f 5 ) | sed s/".m4v"//g ) | sed s/".mp4"//g ) | sed s/".f4v"//g ) | sed s/".mpg"//g ) | sed s/".wmv"//g )
   	rm "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt"
   #Encode
	FILENAME=$(((((basename "$SOURCE" ) | sed s/".mp4"//g ) | sed s/".m4v"//g ) | sed s/".f4v"//g ) | sed s/".mkv"//g)
	echo "$FILENAME" > "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt"
	SUBTITLE="/Volumes/Mac Pro Storage/1-Subtitle/$FILENAME.srt"

if [ "$ENCODE" = "iTouch" ] ;
	then
		echo "Encoding for iPod Touch"
	   "$PATHTOHANDBRAKECLI/HandBrakeCLI" -e x264 -q 20.0 -a 1 -E faac -B 128 -6 dpl2 -R 48 -D 0.0 -f mp4 -X 480 -m -x cabac=0:ref=2:me=umh:bframes=0:subme=6:8x8dct=0:trellis=0:weightb=0 --deinterlace --decomb --detelecine --subtitle scan --subtitle-forced scan -i "$SOURCE" -o "$DESTINATION"
fi
if [ "$ENCODE" = "SDAppleTV" ] ;
	then
		echo "Encoding for AppleTV in Standard Definition"
	   "$PATHTOHANDBRAKECLI/HandBrakeCLI" -e x264 -q 19.25 -a 1,1 -E ca_aac,ac3 -B 160,160 -6 dpl2,auto -R 48,Auto -D 0.0,0.0 -f mp4 -4 --loose-anamorphic -m -x ref=3:mixed-refs=1:bframes=3:me=hex:subq=7:b-adapt=2:8x8dct=1:weightb=0:trellis=0:weightp=0:vbv-maxrate=9500:vbv-bufsize=9500 --deinterlace --decomb --detelecine --subtitle scan --subtitle-forced scan -i "$SOURCE" -o "$DESTINATION"
fi
if [ "$ENCODE" = "HDAppleTV" ] ;
	then
		echo "Encoding for AppleTV in High Definition"
	   "$PATHTOHANDBRAKECLI/HandBrakeCLI" -e x264 -q 23.0 -a 1,1 -E ca_aac,ac3 -B 160,160 -6 dpl2,auto -R 48,Auto -D 0.0,0.0 -f mp4 -4 -X 1080 -M 709 --loose-anamorphic -m -x ref=3:mixed-refs=1:bframes=3:me=hex:subq=7:b-adapt=2:8x8dct=1:weightb=0:trellis=0:weightp=0:vbv-maxrate=5000:vbv-bufsize=5000 --deinterlace --decomb --detelecine --subtitle scan --subtitle-forced scan -i "$SOURCE" -o "$DESTINATION"
fi
if [ "$ENCODE" = "SDAppleTV & iTouch" ] ;
	then
		echo "Encoding for AppleTV in Standard Definition"
	   "$PATHTOHANDBRAKECLI/HandBrakeCLI" -e x264 -q 19.25 -a 1,1 -E ca_aac,ac3 -B 160,160 -6 dpl2,auto -R 48,Auto -D 0.0,0.0 -f mp4 -4 --loose-anamorphic -m -x ref=3:mixed-refs=1:bframes=3:me=hex:subq=7:b-adapt=2:8x8dct=1:weightb=0:trellis=0:weightp=0:vbv-maxrate=9500:vbv-bufsize=9500 --deinterlace --decomb --detelecine --subtitle scan --subtitle-forced scan -i "$SOURCE" -o "$DESTINATION"
		echo "Encoding for iPod Touch"
	   "$PATHTOHANDBRAKECLI/HandBrakeCLI" -e x264 -q 20.0 -a 1 -E faac -B 128 -6 dpl2 -R 48 -D 0.0 -f mp4 -X 480 -m -x cabac=0:ref=2:me=umh:bframes=0:subme=6:8x8dct=0:trellis=0:weightb=0 --deinterlace --decomb --detelecine --subtitle scan --subtitle-forced scan -i "$SOURCE" -o "$DESTINATIONITOUCH"
fi
if [ "$ENCODE" = "HDAppleTV & iTouch" ] ;
	then
		echo "Encoding for AppleTV in High Definition"
	   "$PATHTOHANDBRAKECLI/HandBrakeCLI" -e x264 -q 23.0 -a 1,1 -E ca_aac,ac3 -B 160,160 -6 dpl2,auto -R 48,Auto -D 0.0,0.0 -f mp4 -4 -X 1080 -M 709 --loose-anamorphic -m -x ref=3:mixed-refs=1:bframes=3:me=hex:subq=7:b-adapt=2:8x8dct=1:weightb=0:trellis=0:weightp=0:vbv-maxrate=5000:vbv-bufsize=5000 --deinterlace --decomb --detelecine --subtitle scan --subtitle-forced scan -i "$SOURCE" -o "$DESTINATION"

		echo "Encoding for iPod Touch"
	   "$PATHTOHANDBRAKECLI/HandBrakeCLI" -e x264 -q 20.0 -a 1 -E faac -B 128 -6 dpl2 -R 48 -D 0.0 -f mp4 -X 480 -m -x cabac=0:ref=2:me=umh:bframes=0:subme=6:8x8dct=0:trellis=0:weightb=0 --deinterlace --decomb --detelecine --subtitle scan --subtitle-forced scan -i "$SOURCE" -o "$DESTINATIONITOUCH"
fi
   #Wait for encoding to finish
   wait
   
   # Move the finished encode to its finished location
	DESTINATION2=$(basename "$DESTINATION" )
	echo "$DESTINATION2" > "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt"
	DESTINATION3=$((((((((grep "$DESTINATION2" "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt" ) | sed s/".m4v.m4v"/".m4v"/g ) | sed s/".mp4"//g ) | sed s/".f4v"//g ) | sed s/".wmv.m4v"/".m4v"/g ) | sed s/".mp4.m4v"/".m4v"/g ) | sed s/".avi.m4v"/".m4v"/g ) | sed s/".mkv.m4v"/".m4v"/g )
	echo "$DESTINATION3"
	rm "/Volumes/Mac Pro Storage/0-Temp Files/filename.txt"
   mv "$DESTINATION" "$ENCODEDDIRECTORY/$DESTINATION3"
   

   
	if [ -f "$ENCODEDDIRECTORY/$DESTINATION3" ] ;
		then
		   echo "Completed encode of $SOURCE"
		   echo
		   # Move the DVD Source to its completed location
		if [ -f "$EXTERNALSTORAGE2/.flag" ] ; 
			then
				echo ""
		   		cp -Rv "$SOURCE" "$EXTERNALSTORAGE2/" 
		   		rm -Rv "$SOURCE"
			else
				echo "Moving Completed Source to Storage"
			 	mv "$SOURCE" "$COMPLETEDDVDS/"
		fi
	else
		echo "DVD Rip Failed Please See Log File"
		mv "$SOURCE" "$RIPFAILED"/
	fi

done
IFS=$OLDIFS

echo "Finished processing videos"

# Remove the lock file so that this script will run next time it is called
rm "$RIPDIRECTORY/ProcessingVideo.flag"
