#!/bin/bash

# ComChecker Linux & Mac v 0.6 Copyright 2009, Brandon Jenkins
# This is the same script used on the OS X version with exception to the inclusion of the
# user defined settings. It is a separate file on the Mac. 

# Defaults and config options for Linux
# Simultaneous comskip executions
SIMUL=5

# Adjust this value to affect the priority of a comskip execution. Value range: 0 - 19.
NICE=0

# Path to wine inside of the wine.bundle
WINEPATH=/usr/bin

# Path to comskip.exe and ini.
CSPATH=/opt/sagetv/comskip

# Path to tv files. Space delimited for multiples.
TVPATH=( /var/media/tv /var/media/tv1 )

# Video file types to scan
VTYPE=( mpg ts )

# Cpu Loading Multiplier - This will dermine what cpu loading to apply to a scanning of a file type. Create Variables based on types used above.
# A setting of one will run the number of jobs allowed per SIMUL value. A setting less than 1 will result in more jobs than SIMUL, greater than 1 will result in less. 

CPU_LOAD_mpg=1
CPU_LOAD_ts=2

# Comskip files to look for
CHKEXT=( txt log edl xml logo )

# If files exist with these extentions, keep all files related to video
KEEP=( ts mpg mp4 ps )

# Set the interval for checking the directory. Recommend 60 seconds. Live scanning is faster.
DELAY=60

# SageTV Specific feature: Check recording channel and skip if listed.
SAGETV_ENABLE=FALSE
SAGETV_SERVER=
SAGETV_SERVER_PORT=
SAGETV_SERVER_USER=
SAGETV_SERVER_PASS=
SAGETV_SKIP_CHAN=(  ) # This is the channel id. eg ( NBC PBS )


if [[ $1 ]]; then . $1; fi

if [ -e "$WINEPATH/Wine.bundle" ]; then APPLE_APP="Wine.bundle/Contents/bin/"; fi

while [ 1 ] ; do
	for (( x = 0 ; x < ${#TVPATH[@]} ; x++ )); do
		echo
		echo "Processing Videos in ${TVPATH[$x]}.."
		echo
		for (( n = 0 ; n < ${#VTYPE[@]} ; n++ )); do
			echo "	Checking for ${VTYPE[$n]} videos."
			for VIDEO in $(find ${TVPATH[$x]} -type f \( -name "*.${VTYPE[$n]}" \)); do
				#echo "		Found $VIDEO checking processed..."
				PROCESSED=0
				EPISODE=`basename $VIDEO | cut -d'.' -f1`
				for (( i = 0 ; i < ${#CHKEXT[@]} ; i++ )); do
					if [ -f "${TVPATH[$x]}/$EPISODE.${CHKEXT[$i]}" ]; then
						#echo "			Already processed."
						PROCESSED=1
					fi
				done
				
				if [ ! $PROCESSED -eq 1 ]; then
					CPU_LOAD_MULTIPLIER=$(eval echo \$"CPU_LOAD_`echo ${VTYPE[$n]}`")
					let CPU_LOAD_VALUE=$SIMUL/$CPU_LOAD_MULTIPLIER
					if [ $CPU_LOAD_VALUE -gt `ps -ef | grep comskip | grep -v grep | wc -l | sed 's/ //g'` ]; then
						if [ -f "$VIDEO" ]; then
							# Check to see if file is on do not process channel list
							if [ $SAGETV_ENABLE == "TRUE" ]; then
								CHAN_NAME=$(curl --user $SAGETV_SERVER_USER:$SAGETV_SERVER_PASS --silent \
									http://$SAGETV_SERVER:$SAGETV_SERVER_PORT/sagex/api?c=GetMediaFileForFilePath\&1=$VIDEO | grep AiringChannelName | cut -d[ -f3 | cut -d] -f1)
								if [ $(echo ${SAGETV_SKIP_CHAN[*]} | grep $CHAN_NAME | wc -l) -eq 1 ]; then
									echo "Skip Video: $VIDEO"
									touch $(eval echo ${VIDEO} | cut -c-$(expr $(echo ${VIDEO} | wc -m) - $(echo ${VTYPE[$n]} | wc -m)))edl
								else
									echo "			Run Comskip on $VIDEO"
									nohup $(which nice) -n $NICE "$WINEPATH/${APPLE_APP}wine" "$CSPATH/comskip.exe" --ini="$CSPATH/comskip.ini" "$VIDEO" 2>/dev/null 1>/dev/null &
								fi
							else
								echo "			Run Comskip on $VIDEO"
								nohup $(which nice) -n $NICE "$WINEPATH/${APPLE_APP}wine" "$CSPATH/comskip.exe" --ini="$CSPATH/comskip.ini" "$VIDEO" 2>/dev/null 1>/dev/null &
							fi
						fi
					else
					    echo "			Waiting for other Comskip to finish."
					fi
				fi
			done
		done
		echo	
		echo "Looking for old files..."
		echo
		FILE_LIST=$(find ${TVPATH[$x]} -name *.`echo ${CHKEXT[*]} | sed 's/ / -o -name *./g'` | sed 's/.*\///' | cut -d '.' -f1 | uniq)
		for DELME in $FILE_LIST
		do
			FILE_EXIST=0
			for (( KEEPME = 0 ; KEEPME < ${#KEEP[@]} ; KEEPME++ )); do
				if [[ -f ${TVPATH[$x]}/$DELME.${KEEP[$KEEPME]} ]]; then
					# echo "Found ${TVPATH[$x]}/$DELME.${KEEP[$KEEPME]}"
					FILE_EXIST=1
				fi
			done
			if [ $FILE_EXIST == 0 ]; then
				echo "	Removing $DELME.*"
				rm ${TVPATH[$x]}/$DELME.*
			fi	
		done
	done
	echo
	echo "Waiting for $DELAY seconds"
	sleep $DELAY
done
