#!/bin/bash

if [ -z $2 ]; then
  echo "Error"
  exit 1
else
  CONVERTDIR=$2
fi

EXPORTDIR="/media/convert/"
VIDEODIR=/video0
LOGFILE=/var/log/convert2wmv_high.log

TEMPDIR="/video0/$RANDOM"
TEMPFILE="$RANDOM"
OUTFILE=`echo $CONVERTDIR | sed s#$VIDEODIR## | sed s#/#_#g | sed s/#5FTOWMVHIGH// | sed s/#5FNONOAD// | sed s#^-##`.avi
#echo "OUTFILE: $OUTFILE"

if [ `echo $CONVERTDIR|grep TOWMVHIGH` ]; then
	echo "`date`: Convert Recording \"$2\" to WMV start" 2>&1 >> $LOGFILE
	mkdir -p $TEMPDIR
	cd $TEMPDIR
	echo "Sync VDR Recording and convert to mpeg2" 2>&1 >> $LOGFILE
	eval nice -15 vdrsync.pl "$CONVERTDIR" -mpeg2 -o $TEMPDIR -basename $TEMPFILE 2>&1 >> $LOGFILE
	if [ $? == 0 ]; then
		echo "Encode synced mpeg2 to WMV" 2>&1 >> $LOGFILE
		eval nice -15 mencoder $TEMPFILE\1.mpg -o $EXPORTDIR/$OUTFILE -ni -ovc lavc -oac lavc -lavcopts vcodec=wmv2:vbitrate=2048:acodec=mp2:abitrate=192:autoaspect 2>&1 >> $LOGFILE
		if [ $? == 0 ]; then
			echo "Delete VDR Recording after successful converting" 2>&1 >> $LOGFILE
			rm -Rf $CONVERTDIR 2>&1 >> $LOGFILE
			# Update VDR Video Anzeige
			touch $VIDEODIR/.update
			# Update XXV Aufnahmenübersicht
			wget -O /dev/null http://localhost:8080/?cmd=rupdate
		fi
	else
		echo "Error while syncing" 2>&1 >> $LOGFILE
	fi
	cd - 	
	rm -rf $TEMPDIR  2>&1 >> $LOGFILE
	echo "`date`: Convert Recording end" 2>&1 >> $LOGFILE
	echo "________________________________________________" 2>&1 >> $LOGFILE
fi
