#!/bin/sh



# *** This is just a small script, which does the following:
# - Encodes VOB-files to AVI-files, scaling to 320x240
# - Merges them into one AVI
# - Splits this file into 4 parts
#
# You need mencoder and transcode to run this script
#
# Eugene Suchkov <me@cityhawk.ru> 


NAME=$1
if [ -z $1 ]; then NAME="UnknownMovie"; fi


function getmencoder {
	MENCODER=`which mencoder`
	RES=$?
	if [ $RES = 1 ]; then
	 	echo "No mencoder found. Please install mencoder"
		return 1
	else
		return 0 
	fi
	}

function getavisplit {
	 AVISPLIT=`which avisplit`
	 RES=$?
	 if [ $RES = "1" ]; then
	 	echo "No avisplit found. Please install transcode"
	 	return 1
	 else	
	 	return 0
	 fi

	}

function getavimerge {
	 AVIMERGE=`which avimerge`
	 RES=$?
	 if [ $RES = 1 ]; then
	 	echo "No avimerge found. Please install transcode"
	 	return 1 
	 else
	 	return 0
	 fi

	}

getmencoder
if [ $? = "1" ]; then exit; fi
getavisplit
if [ $? = "1" ]; then exit; fi
getavimerge
if [ $? = "1" ]; then exit; fi

if [ ! -w `pwd` ]; then echo "I can't run from this dir! No permissions to write :(" ;exit; fi

echo Mencoder detected as $MENCODER
echo Avisplit detected as $AVISPLIT
echo Avimerge detected as $AVIMERGE

VOBFILES=`find * -maxdepth 1 -iname "*.vob"`


echo "Encoding VOBs..."
i=1
for VOBFILE in $VOBFILES 
do
	OUTPUTTEMPAVI[$i]=$VOBFILE.avi
	$MENCODER $VOBFILE -oac mp3lame -ovc lavc -lavcopts vcodec=mpeg4:vhq:vqmin=2:vqmax=20:vmax_b_frames=2:vbitrate=100:vqcomp=0.6 -vf scale=320:240,eq=15 -ofps 20 -zoom -sws 2 -lameopts cbr:br=32:aq=0:mode=3 -o ${OUTPUTTEMPAVI[$i]}
	i=$[$i+1]
done

echo "Merging them..."
$AVIMERGE -o $NAME-full.avi -i ${OUTPUTTEMPAVI[*]}

FULLSIZE=`du -m $NAME-full.avi | awk '{print $1}'`
PARTSIZE=$[($FULLSIZE/4)+1]

echo "Splitting into 4 parts..."
$AVISPLIT -s $PARTSIZE -o $NAME -i $NAME-full.avi

echo "Cleaning the garbage..."
rm -f ${OUTPUTTEMPAVI[*]}





