#!/bin/sh

#functions
f_suffix()
{
	echo "${1##*.}"
}


#parameters
if [ $# -eq 1 ]
then 
	#parameter
	path="$1"
else
	#default
	path="/data/media/movies"
fi


#main
find "$path" -not -name '*.fixed.*' \( -iname '*.avi' -or -iname '*.mpg' -or -iname '*.mpeg'  \)  -type f | \
while read i
do
	suffix=$(f_suffix "$i")
	filename_out="${i%.avi}.fixed.${suffix}"
	filename_tmp="${i}.tmp"	

	echo "Repair file ${i}"
		
	#remove old temp file
	if [ -f $filename_tmp ]
	then
		echo "rm ${filename_tmp}"
		rm "${filename_tmp}"
		
	fi

	if [ -f $filename_out ]
	then
		#file is fixed, remove original file
                echo "rm ${i}"
                rm "${i}"
	else
		#repair video file
		mencoder -idx "$i" -ovc copy -oac copy -o "${filename_tmp}"
	
		#remove source file only, if mencoder was successfully finished
		if [ $? -eq 0 ]
		then
			mv "${filename_tmp}" "${filename_out}"

			#delete original movie
			echo "rm ${i}"
			rm "${i}"
		fi
	fi

done

