#!/bin/bash
hb=/usr/bin/HandBrakeCLI
ext=ts
INDIR="$1"
LOGFILE="$INDIR/convertTS.log"
OUTDIR="/data/video.00/Filme"
NASDIR="/mnt/nfs/nas/Videos/Aufnahmen/"

echo "Start converting $INDIR" >> $LOGFILE
TITLE=`egrep "^T" "$INDIR/info"  |sed -e "s/^T //" | sed "s_/_ _g" | sed "s/:/_/g"`
EPISODE=`egrep "^S" "$INDIR/info"  |sed -e "s/^S //" | sed "s_/_ _g" | sed "s/:/_/g"`
OUTFILE="$TITLE"

if [ "x$EPISODE" = "x" ]; then
	tmp1="${INDIR%.rec/}"
	EPISODE="${tmp1##/*/}"
	OUTFILE="${OUTFILE}_${EPISODE}"
else
	OUTFILE="${OUTFILE} - ${EPISODE}"
fi

CONCATFILE=film.$ext
OUTFILE="$OUTDIR/$OUTFILE.mkv"
echo CONCATFILE=$CONCATFILE OUTFILE=$OUTFILE

cd "$1"
copystring=""
for infile in 0*$ext
  do
    copystring="$copystring $infile"
  done
cat $copystring > $CONCATFILE 
#cp $CONCATFILE $NASDIR

#AC3TRACKS=`ffmpeg -i $INFILE 2>&1  |grep "Audio" |grep "ac3" |sed -e 's/.*Stream #0.\([0-9]\).*/\1/g'`
#AC3TRACKS=`ffmpeg -i $INDIR/00001.ts 2>&1  |grep "Audio" |grep "ac3" |sed -e 's/.*Stream #0.\([0-9]\).*/\1/g'`
#MP2TRACKS=`ffmpeg -i $INFILE 2>&1  |grep "Audio" |grep "mp2" |grep "stereo" |sed -e 's/.*Stream #0.\([0-9]\).*/\1/g'`
#MP2TRACKS=`ffmpeg -i $INDIR/00001.ts 2>&1  |grep "Audio" |grep "mp2" |grep "stereo" |sed -e 's/.*Stream #0.\([0-9]\).*/\1/g'`

AUDIOTRACKS=""
for line in `ffmpeg -i "$CONCATFILE" 2>&1  |grep "Audio" |grep "ac3" |sed -e 's/.*Stream #0.\([0-9]\).*/\1/g'`
  do
    if [ "x$AUDIOTRACKS" = "x" ]; then
	  AUDIOTRACKS="$line"
	  AUDIOENCODE="copy:ac3"
	else
	  AUDIOTRACKS="$AUDIOTRACKS,$line"
	  AUDIOENCODE="$AUDIOENCODE,copy:ac3"
	fi
  done
  
for line in `ffmpeg -i "$CONCATFILE" 2>&1  |grep "Audio" |grep "mp2" |grep "stereo" |sed -e 's/.*Stream #0.\([0-9]\).*/\1/g'`
  do
    if [ "x$AUDIOTRACKS" = "x" ]; then
	  AUDIOTRACKS="$line"
	  AUDIOENCODE="lame"
	else
	  AUDIOTRACKS="$AUDIOTRACKS,$line"
	  AUDIOENCODE="$AUDIOENCODE,lame"
	fi
  done

echo AUDIOTRACKS=$AUDIOTRACKS AUDIOENCODE=$AUDIOENCODE
  
AUDIO="-a $AUDIOTRACKS  -E $AUDIOENCODE --audio-fallback lame"
CROP="--crop 0:0:0:0"

nice -n 19 /usr/bin/HandBrakeCLI -i "$CONCATFILE" -o "$OUTFILE" -f mkv -e x264 --vfr -w 720 --loose-anamorphic --modulus 2 --x264-profile=high --h264-level="4.1" $AUDIO -b 2000 --verbose=2 $CROP 2>> $LOGFILE 1>> $LOGFILE
rm $CONCATFILE >> $LOGFILE
echo "Converted $INDIR to $OUTFILE" >> $LOGFILE
